takeUntilDestroyed() 只能在注入上下文中使用

Ben*_*cot 22 rxjs angular

我正在尝试用 Angular 的新takeUntilDestroyed().

\n

但我一开始就犯了错误。

\n
\n

NG0203:takeUntilDestroyed() 只能在注入上下文中使用,例如构造函数、工厂函数、字段初始值设定项或与runInInjectionContext. 欲了解更多信息,请访问https://angular.io/errors/NG0203

\n
\n

博客文章说:

\n
\n

默认情况下,该运算符将注入当前的清理上下文。例如,在组件中使用,它将使用组件\xe2\x80\x99s的生命周期。

\n
\n

文档确认注入上下文是可选的这篇深入的文章展示了它在OnInit没有上下文的情况下的用法。\n这就是我如何使用它。

\n
  public ngOnInit(): void {\n    this.route.firstChild.paramMap.pipe(\n      takeUntilDestroyed()\n    ).subscribe((res: ParamMap) => {\n      ...\n    });\n
Run Code Online (Sandbox Code Playgroud)\n

如何解决这个问题?

\n

Joh*_*ate 46

destroyRef每当您takeUntilDestroyed()在注入上下文之外使用时,您都需要传递。您可以将注入上下文视为代码中在实例化类(在本例中为组件)之前运行的空间。类的构造函数是注入上下文的一个示例,因为构造函数内的代码在类实例化之前运行。另一个例子是类字段声明,每当声明一个字段时,您必须直接为其赋值或在构造函数中赋值,这是因为该值必须在实例化时已知,这告诉我们此赋值发生在注入上下文

这个工作正常:

export class FooCmp implements OnInit {
    route = inject(ActivatedRoute);
    params$ = this.route.firstChild.paramMap.pipe(takeUntilDestroyed())

    ngOnInit() {
        this.params$.subscribe(res => {/* some operation */})
    }
}

export class BarCmp {
    constructor(private route: ActivatedRoute) {
        this.route.firstChild.paramMap
        .pipe(takeUntilDestroyed())
        .subscribe(res => {
            // some operation
        })
    }
}
export class BazCmp implements OnInit {
    route = inject(ActivatedRoute)
    destroyRef = inject(DestroyRef)

    ngOnInit() {
        this.route.firstChild.paramMap
        .pipe(takeUntilDestroyed(this.destroyRef))
        .subscribe(res => {/* some operation */})
    }

}
Run Code Online (Sandbox Code Playgroud)

这个不会:

export class FooCmp implements OnInit {
    route = inject(ActivatedRoute);

    ngOnInit() {
        this.route.firstChild.paramMap.pipe(takeUntilDestroyed())
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:链接到有关注入上下文的 Angular 文档:https://angular.io/guide/dependency-injection-context

  • 我认为 takeUntilDestroyed() 更聪明一点...... (8认同)