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

我怕爱的太早我们不能终老 提交于 2020-01-14 12:17:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/51990188/the-semantics-of-injectableprovidedin-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!