angularangular2-directivesangular2-pipe

Register service in root AppModule or root AppComponent


Everywhere, it is recommended to register a service in root AppModule providers array and avoid using providers array of root AppComponent. When should someone register a service in root AppComponent? Any practical example. What is the advantage of registering service in root AppModule compared to root AppComponent?


Solution

  • When registered at the root, the provided service is created as a singleton, as opposite to providing in the component, it will be created as many instances as you use the component.

    In other words:
    The service injected at the root level will be accessible in the entire application.
    The service provided at the component level will be available only on that component and its children.

    In case you inject the service in multiple components (@Component({ ...providers: [] ..}), each will get it's own instance and their children will share that same instance.
    If you inject in root level (@NgModule({ ... providers: []}), all components will share the same instance.

    Read more here