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

查看:32
本文介绍了角度 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 {}

所以,

  • 应该使用哪种方法让注入器知道它应该注入的服务?
  • 模块 providers 数组方法会被弃用吗?
  • Which method should be used to make the injector aware of the service that it should inject?
  • Will the module providers array method be deprecated?

推荐答案

基本上你可以使用任何一个,但根据新的 CLI provideIn 将在创建 service 时自动添加

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

#providedIn

#providedIn

现在有一种新的、推荐的、直接注册提供者的方法在 @Injectable() 装饰器中,使用新的 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.

更多信息请参考这里

  • https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/
  • https://angular.io/guide/dependency-injection#injectable-ngmodule-or-component
  • https://angular.io/guide/hierarchical-dependency-injection#moduleinjector [As suggested by Tuan-Tu in comment below]

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

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