| fun-with-more-di | Advanced Topics in Angulars Dependency Injection |
- We understood that the type of the requested injection does not always accurately describe the intent of the required object. Sometime the type can be something like "string" or "number" and you to further describe the requested item
- Injection Tokens Allow us to define something that needs to be injected, regardless of its type
- We create an injection token by exporting a constant of type
InjectionToken<T>whereTis the data type. - We provide it by using the injection token in the
provideproperty of the provider object. - We consume it using the
@Inject(token)decorator - We can also mark it as optional using the
@Optional()decorator
- We create an injection token by exporting a constant of type
- We have already seen the
useClassanduseExistingproviders in Module 05 - We saw how to privde an exact value using the
useValueprovider. - We saw how to use the
useValueprovider to provide a token of type function, so that the function can later be called lazily. - We saw how to use the
useFactoryprovider, to calculate the value using a method that is called when the value is first needed to be provided. - We saw how to use the
useFactoryprovider, to provide a value of type function (a function that returns a function). - We saw that the
useFactoryprovider may also receive injectable prameters- These are set using the
depsproperty of the provider. - In the
depsproperty, we list the tokens that can be used to populate each parameter - We saw that we can use
closureto create a function value, that uses on of these parameters.
- These are set using the
- We saw that we can define a token of type array, and then provide each item seperately.
- We saw that when several modules provide the same token, only one provider takes effect.
- But, when we use the
multi:truesettings, the various providers are accumulated, and all the values are injected.
- We saw the
APP_INITIALIZERtoken, which is of type function, that either returnsvoid,Promise<voidorObservable<void>. - We saw that the actualy type that angular expects is an array of initialization methods.
- We saw that each module may supply several initializers using the
multisettings. - We saw that in order to initalize a service, we need to:
- use the
useFactoryprovider - supply the service as parameter using the
depsproperty - return a function object that calls the init method
- notice that we take advantage of the closure feature.
- use the
- We saw that angular will then await the returned promises and will start rendering the application only once the initializers are all complete.