角度6依赖注入 [英] angular 6 dependency injection

查看:102
本文介绍了角度6依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 6的最新版本中,使用服务元数据中的 providedIn 属性在模块中注册服务:

In the latest release of Angular 6, a service is registered in a module using the providedIn property in the service metadata:

@Injectable({
  providedIn: 'root',
})
export class HeroService {}

但是文档仍然指的是在模块 providers 数组中注册服务在模块元数据中就像我们在Angular 5中所做的那样:

However the documentation still also refers to registering the service in the module providers array in the module metadata just like we did in Angular 5:

@NgModule({
  providers: [HeroService],
})
export class AppModule {}

因此应该使用哪种方法使喷射器知道它应注入的服务&模块提供者的数组方法是否会被弃用?

so which method should be used to make the injector aware of the service that it should inject & is the module provider's array method will be deprecated?

推荐答案

基本上你可以使用其中任何一种,但是根据新的CLI provideIn 将在创建服务时自动添加

Basically you can use either, But as per new CLI provideIn will be automatically added while creating service


现在有一种新的推荐方式来注册提供者,直接在$ code> @Injectable()<
内/ code> decorator,使用新的providedIn
属性。它接受'root'作为
应用程序的值或任何模块。当您使用'root'时,您的注射剂将在应用程序中作为单身注册
,您无需将其添加到
根模块的提供者。同样,如果你使用 providedIn:UsersModule
注入可注册为
UsersModule 没有将它添加到模块的提供者。

There is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module.

这种新的方法已被引入,以便在
应用程序中有更好的树状结构。目前,添加到模块
的提供者的服务将最终出现在最终的捆绑包中,即使它没有在
应用程序中使用,这有点让人感到难过。

This new way has been introduced to have a better tree-shaking in the application. Currently a service added to the providers of a module will end up in the final bundle, even if it is not used in the application, which is a bit sad.

有关详细信息,请参阅此处

For more information please refer here

  • https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/
  • https://angular.io/guide/dependency-injection#injectable-ngmodule-or-component

这篇关于角度6依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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