[英]Why doesn't Angular2 auto detect directives and providers used in a component definition?
For custom directives used inside the template, I guess it might make sense for Angular to not know the new html elements/attributes until we tell it in the "directive" property of the Component function. 对于模板内部使用的自定义指令,我猜想Angular在知道我们在Component函数的“ directive”属性中不知道新的html元素/属性时可能是有意义的。
However, what I don't understand why Angular doesn't figure out what providers we want for dependency injection even though we pass those services names via parameters in the Component constructor function. 但是,我不明白为什么Angular不能弄清楚我们想要什么样的提供程序进行依赖注入, 即使我们通过 Component构造函数中的参数传递了这些服务名称 。 Was this a design decision, or is Angular unable to figure out the providers needed just from the constructor parameters?
这是设计决定,还是Angular无法仅从构造函数参数中找出所需的提供程序?
In essence, why do we need providers: [HeroService],
when we already have constructor(heroService: HeroService) {...}
? 本质上,为什么我们需要
providers: [HeroService],
当我们已经有了constructor(heroService: HeroService) {...}
?
Providers define two things 提供者定义两件事
the scope 范围
Where you define a provider defines what instance will be injected. 在定义提供程序的位置定义将要注入的实例。 Providers added at the root share a single instance with the whole application.
在根目录添加的提供程序与整个应用程序共享一个实例。
Providers on a component override root providers for themselves and their subtree. 组件上的提供程序将覆盖其自身及其子树的根提供程序。
the concrete value 具体价值
You can have a provider like 您可以有一个像
{ provide: HeroService, useClass: SuperHeroService }
{ provide: 'SomeConfig', useValue: 'someValue' }
{ provide: Foo, useFactory: () => new Bar() }
Already taken care of actually. 已经照顾好了。 RC5 removed a LOT of boilerplate code.
RC5删除了很多样板代码。
So you no longer need the 'directives' or 'providers' syntax in your @Component or @Directive declarations. 因此,您不再需要@Component或@Directive声明中的“指令”或“提供程序”语法。
Link: http://angularjs.blogspot.com/2016/08/angular-2-rc5-ngmodules-lazy-loading.html 链接: http : //angularjs.blogspot.com/2016/08/angular-2-rc5-ngmodules-lazy-loading.html
This was definitely a design decision, because in some cases you might want a singleton service across your entire application and in another case you maybe need more instances of the same service. 这绝对是一个设计决定,因为在某些情况下,您可能希望在整个应用程序中使用单例服务,而在另一种情况下,您可能需要同一服务的更多实例。
And regarding to the answer by @cDecker32 you still need to register the providers, only now you do it in @NgModules
take a look at this documentation: 关于@ cDecker32的答案,您仍然需要注册提供程序,只有现在您在
@NgModules
进行操作,才能查看此文档:
https://angular.io/docs/ts/latest/guide/ngmodule.html https://angular.io/docs/ts/latest/guide/ngmodule.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.