I'd like to know if these two blocks of code are equivalent or not.
Can I use providedIn
with the same result of forRoot
?
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
}
vs
@Injectable()
export class MyService {
constructor() { }
}
@NgModule({
imports: []
})
export class MyModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
MyService
]
};
}
}
@NgModule({
imports: [
MyModule.forRoot()
],
bootstrap: [AppComponent]
})
export class AppModule { }
[I would still keep my MyModule
for single use with the providedId
singleton services]
providedIn is the new Angular way of doing DI. providedIn was brought since Angular 6. The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided.
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.
The forRoot static method is the method that configures the root routing module for your app. When you call RouterModule. forRoot(routes) , you are asking Angular to instantiate an instance of the Router class globally.
There are multiple ways to prevent this: Use the providedIn syntax instead of registering the service in the module. Separate your services into their own module. Define forRoot() and forChild() methods in the module.
Using providedIn
vs providers[]
:
providedIn
is the new Angular way of doing DI. providedIn
was brought since Angular 6
The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided
Using providedIn: 'root'
removes the need to import the library module at all, we can simply inject needed services and it just works
Yes, forRoot
and provideIn
both are equivalent since both will create the only and only one singleton for the app. Even though it being loaded in lazy loaded component.
Refer this nice article on it - https://medium.com/@chrishouse/when-to-use-angulars-forroot-method-400094a0ebb7
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