Yesterday, I introduced an injection context, and we saw a few locations where we could inject dependencies. This can be limiting in scenarios where we call a method that creates and returns an Observable outside of an injection context, as we can’t always initialize observables in a constructor. Does that mean we cannot use the takeUntilDestroyed
operator in those scenarios?
No, because we can store our injector for later use using the following approach:
The key is to use the runInInjectionContext
function and pass the injector as a parameter.
For the takeUntilDestroyed
operator, we can inject a DestroyRef
in our injection context and then use it as a parameter whenever we need that operator:
Problem solved! We can use all these tools from the framework in any place we want, thanks to EnvironmentInjector
and DestroyRef
.