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 })
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
.
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})
]);
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.
来源:https://stackoverflow.com/questions/38144641/what-is-multi-provider-in-angular2