Search code examples
angulartypescriptprogressive-web-appsangular-providersangular-dependency-injection

The semantics of @Injectable(providedIn: 'root')?


Just want to make sure I understand the semantics of @Injectable(providedIn: 'root'). Prior to Angular 6 if we import a module from NPM that contains a service we would declare that module in our app module such that the entire application has access to the service. Something like this:

    import { SomeNPModule } from '@ngx/SomeNPModule';

    @NgModule({
    imports: [
        BrowserModule,
        SomeNPModule
    ]
    })
    export class AppModule {}

Now we can inject the SomeService that the module provides because we have imported the module. With Angular 6 the need to import the SomeNPModule into the AppModule is removed because we are using @Injectable(providedIn: 'root) on the service itself, and when the annotation runs it automatically makes the service available in the root injection container?

Update

So we have the answer, but I think it's partially complete in the sense that if we want to configure the service, the this is typically done via the forRoot method on the service's module...as is done via the Router. So assuming that we don't want to configure the service, all we need to do is inject it, but if we want a configured service, we need to follow the Router pattern. Correct me if I made any mistakes in the comments please.


Solution

  • When you write @Injectable(providedIn: 'root') this means that the service in singleton for whole application and you can inject in anywhere in the application.

    When you want to make service singleton only for an exact module, you need to assign your module as the parameter to the providedIn - @Injectable(providedIn: MyModule)

    The only other action required in order to use the @Injectable decorated service is to import it and constructor inject it and that's it. No need to import it in the AppModule.