Injection Beyond Classes
So far providers
have been used with Angular's @NgModule
meta in anarray. providers
have also all been class identifiers. Angular letsprogrammers specify providers with a more verbose "recipe". This is done withby providing Angular an Object literal ({}
):
This example is yet another example that provide
s a class, but it does so withAngular's longer format.
This long format is really handy. If the programmer wanted to switch outChatWidget
implementations, for example to allow for a , they coulddo this easily:
The injector can use more than classes though. useValue
and useFactory
aretwo other examples of provider
"recipes" that Angular can use. For example:
In the hypothetical app component, 'Random' could be injected like:
The above example uses Angular's recipe. When Angular is toldto provide
things using useFactory
, Angular expects the provided value to bea function. Sometimes functions and classes are even more than what's needed.Angular has a "recipe" called useValue
for these cases that works almostexactly the same:
In this case, the product of Math.random
is assigned to the useValue
property passed to the provider
.