What is multi provider in angular2

被刻印的时光 ゝ 提交于 2019-11-30 11:10:43

multi: true means that one provider token provides an array of elements. For example all directives for router support routerLink, router-outlet are provided by ROUTER_DIRECTIVES.
If a new provider is registered with the token ROUTER_DIRECTIVES, then it overrides the previously registered directives. If multi: true (on the first registered and the new provider) is set, the new directives are added to the previously registered directives instead of overriding.

When ROUTER_DIRECTIVES is injected (constructor(@Inject(ROUTER_DIRECTIVES) directives) {}) an array of directive instances is injected. It usually doesn't make sense to inject ROUTER_DIRECTIVES. I used it just as an example because it is multi: true.

Arpit Agarwal

Using multi: true tells Angular that the provider is a multi provider. As mentioned earlier, with multi providers, we can provide multiple values for a single token in DI.

Usages:

If we have a couple of directives that should automatically be available in our entire application without anyone having to define them in component decorations, we can do that by taking advantage of multi providers and extending what is being injected for PLATFORM_DIRECTIVES.

@Directive(...)
class Draggable { }

@Directive(...)
class Morphable { }

@Component(...)
class RootCmp { }

and

// at bootstrap
bootstrap(RooCmp, [
  provide(PLATFORM_DIRECTIVES, {useValue: Draggable, multi: true}),
  provide(PLATFORM_DIRECTIVES, {useValue: Morphable, multi: true})
]);

Details

From the docs:

Creates multiple providers matching the same token (a multi-provider). Multi-providers are used for creating pluggable service, where the system comes with some default providers, and the user can register additional providers. The combination of the default providers and the additional providers will be used to drive the behavior of the system.

Source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!