I'm trying to replace my AbstractComponent (all the boilerplate for unsubscribing) with Angular's new takeUntilDestroyed()
.
But am getting an error out of the gate.
NG0203: takeUntilDestroyed() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with
runInInjectionContext
. Find more at https://angular.io/errors/NG0203
The blog post says:
By default, this operator will inject the current cleanup context. For example, used in a component, it will use the component’s lifetime.
The docs confirm that injecting context is optional. And this indepth article shows its use in OnInit
without context.
Here's how I'm using it.
public ngOnInit(): void {
this.route.firstChild.paramMap.pipe(
takeUntilDestroyed()
).subscribe((res: ParamMap) => {
...
});
How can this be resolved?
destroyRef
parameter to pass the current context when outside an injection context.OnInit
is outside the injection context?