@Injectable(providedIn:'root')的语义? [英] The semantics of @Injectable(providedIn: 'root')?

本文介绍了@Injectable(providedIn:'root')的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只想确保我了解 @Injectable(providedIn:'root')的语义.在Angular 6之前,如果我们从NPM导入包含服务的模块,则会在我们的应用程序模块中声明该模块,以便整个应用程序都可以访问该服务.像这样:

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 {}

现在我们可以注入模块提供的 SomeService ,因为我们已经导入了模块.使用Angular 6时,无需将 SomeNPModule 导入到 AppModule 中,因为我们在服务上使用了 @Injectable(providedIn:'root )本身,并且注释运行时会自动在 root 注入容器中提供该服务?

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?

所以我们有答案,但是我认为它在某种程度上是完整的,如果我们要配置服务,通常可以通过服务模块上的 forRoot 方法来完成...通过 Router 完成.因此,假设我们不想配置服务,我们需要做的就是注入它,但是如果要配置服务,我们需要遵循 Router 模式.如果我在评论中有任何错误,请纠正我.

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.

推荐答案

当您编写 @Injectable(providedIn:'root')时,这意味着该服务针对整个应用程序是单一的,并且您可以注入在应用程序中的任何地方.

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.

如果只想为一个确切的模块设置服务单例,则需要将模块作为参数分配给 providedIn - @Injectable(providedIn:MyModule)

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)

要使用 @Injectable 装饰的服务,唯一需要执行的其他操作就是导入它,然后构造函数将其注入,仅此而已.无需将其导入 AppModule .

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.

这篇关于@Injectable(providedIn:'root')的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆