javascript – angular 6依赖注入
作者:互联网
在Angular 6的最新版本中,使用服务元数据中的providedIn属性在模块中注册服务:
@Injectable({
providedIn: 'root',
})
export class HeroService {}
但是,文档仍然指的是在模块元数据中的模块提供程序数组中注册服务,就像我们在Angular 5中所做的那样:
@NgModule({
providers: [HeroService],
})
export class AppModule {}
所以,
>应该使用哪种方法使注射器知道它应该注入的服务?
>是否会弃用模块提供程序数组方法?
解决方法:
基本上你可以使用其中任何一个,但是根据新的CLI,在创建服务时会自动添加provideIn
providedIn
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 useprovidedIn: 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
标签:angular6,javascript,angular,typescript,angular-cli 来源: https://codeday.me/bug/20191003/1850554.html