Inject services from Angular app into custom elements

Viewed 321

I'm currently developping an Angular application based on following principles :

  • A global application with services, components, child modules
  • One of the component load custom elements according to user need
  • These custom element are in fact other angular micro-application (I follow guidelines here : Guide to build angular custom elements)

I choose this design because I want a global application with generic services and side micro-apps (separatly design, built and manage) that use these generic services.

I have a problem and I need help :

  • According to what I've said, I want to share the services of the main angular application into micro-apps.
  • I can share services with my micro-app with Input decorators (for instance : @Input('logService') ) but this is not very convenient as I need as many input as shared services and I need to manage by myself the way these services are used. Example :
//Create custom element 
this.customElement = this.renderer.createElement(customElementTag) as any; 
// Provide it all required service
this.customElement.messageService = this.messageService; 
this.customElement.configurationService = this.configurationService; 
this.customElement.logService = this.logService;

and in custom element

@Input() messageService: MessageService;
@Input() configurationService: ConfigurationService;
@Input() logService: LogService;
  • I would like to inject the services of the global application into micro-apps build in custom elements. I really don't know if this is possible and how to do it... Maybe is there a possibility to get these services and provide them in my app with something like :
CustomElementModule.forRoot({providers:[messageService,configurationService,logService]};
1 Answers

Did you try something like this ?

Inside your angular elements, whenever you inject your services, provide it in the components level using useExisting, like this :

@Component({
  ...
  providers: [
     { provide: MessageService, useExisting: MessageService},
     { provide: ConfigurationService, useExisting: ConfigurationService},
     { provide: LogService, useExisting: LogService},
  ]
})
Related