What is multi provider in angular2

blackHawk picture blackHawk · Jul 1, 2016 · Viewed 17.8k times · Source

I understand that provider is for getting service from another class but what is multi-provider and token thing?

And also when we do multi=true ?

provide(NG_VALIDATORS, { useExisting: class),    multi: true })

Answer

Günter Zöchbauer picture Günter Zöchbauer · Jul 1, 2016

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.