引导vs @component中的Angular2提供程序 [英] Angular2 providers in bootstrap vs @component

查看:54
本文介绍了引导vs @component中的Angular2提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,您可以像这样在bootstrap调用中定义应用程序提供商:

From my understanding, you can define your application providers in your bootstrap call like this:

bootstrap(
  App,
  [disableDeprecatedForms(), provideForms()]]
)

或像这样的根组件中:

@Component({
  selector: 'my-app',
  providers: [disableDeprecatedForms(), provideForms()],
  ...
)

但是,我创建了一个表单验证程序插件,该插件需要provideForms提供程序,并且此指令仅在引导选项时有效。我创建了一个插件来说明问题:如果添加了providerForms,验证程序就可以工作了()进行引导调用。一旦我从引导调用中注释了providerForms(),验证器将不再起作用。我假设组件中的providerForms定义就足够了。有解释吗?

However, I have created a form validator plugin that required the provideForms providers and this directive only works, when the bootstrap options. I have created a plunk to illstrate the problem: the validator works, if I add the providerForms() to the bootstrap call. As soon as I comment out the providerForms() from the bootstrap call, the validator does not work anymore. I assumed that the providerForms definition in the component was sufficient. Any explaination?

推荐答案

Angular2 DI总是向上查找具有所请求依赖项的提供程序。如果通过引导程序实例化的服务需要依赖项,则该依赖项不会注入到树后面的注入中。

Angular2 DI always looks upwards for providers of a requested dependency. If a service that is instantiated by bootstrap requires a dependency than it doesn't get one injected that is provided further down the tree.

bootstrap(...) @Component(...)提供根组件的不是等效的,但是这种区别与根组件内部或其子项或其他后代之一无关。
bootstrap()比根组件高一级。

Providing at bootstrap(...) and @Component(...) of the root component are not equivalent but this distinction is not relevant for everything inside the root component or one of its children or other descendants. bootstrap() is one level higher than the root component.

Angular2样式指南也建议使用根组件而不是 bootstrap(),因为引导程序应保留给系统内容。

The Angular2 style-guide also suggests to prefer the root component over bootstrap() because bootstrap should be reserved for system stuff.

表单和需要在创建第一个组件之前实例化路由器(例如,在V3路由器的早期版本中存在一个错误,该错误中的根组件需要注入 Router 或包含 routerLink ,否则路由器将无法启动)。

Forms and the router need to be instantiated before the first component is created (there was for example a bug in early versions of the V3 router where the root component needed to inject Router or contain a routerLink, otherwise the router wouldn't start up).

因此,由于在创建根组件之前需要实例化某些内容,因此出现了 bootstrap()和根组件变得相关。

So because some things need to be instantiated before the root component gets created the situation comes up where the difference between bootstrap() and root component becomes relevant.

这篇关于引导vs @component中的Angular2提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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