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?
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.
The providedIn allow us to specify how Angular should provide the dependency in the service class itself instead of in the Angular Module. It also helps to make the service tree shakable i.e. remove the service from the final bundle if the app does not use it. ProvidedIn root.
providedIn tells Angular that the root injector is responsible for creating an instance of the your Service. Services that are provided this way are automatically made available to the entire application and don't need to be listed in any module.
Answers: @Injectable needs to be added to every service. @Injectable needs to be added to services that use DI. @Injectable is optional if you don't use the 'providedIn' option. @Injectable in combination with the 'providedIn' option means the service doesn't need to be added in the providers array of a module.
When you write @Injectable(providedIn: 'root')
this means that the service in singletion 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With