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 })
A provider is an instruction to the Dependency Injection system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide.
There are four ways by which you can create the dependency: They are Class Provider (useClass), Value Provider (useValue ), Factory Provider ( useFactory ), and Aliased Class Provider ( useExisting).
Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers is used to register the classes to an angular module as a service. And then, this service classes can be used by other components during the itself creation phase in the module.
An AngularJS service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get , which holds the service factory function.
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}) ]);
Details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With