Angular2 providers in bootstrap vs @component

2019-05-05 17:34发布

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

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

or in your root component like this:

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

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?

1条回答
不美不萌又怎样
2楼-- · 2019-05-05 17:58

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.

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.

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

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).

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.

查看更多
登录 后发表回答