代码之家  ›  专栏  ›  技术社区  ›  dark_gf

角度rxjs获取UntilDestroyed

  •  0
  • dark_gf  · 技术社区  · 2 年前

    只需要对takeUntilDestroyed运算符的文档进行一些澄清,所以阅读此文档: https://angular.io/api/core/rxjs-interop/takeUntilDestroyed ,我没有看到任何单词应该只在“注入”上下文中使用不带params的takeUntilDestroyd(我真的不知道这意味着什么)。所以基本上是“否则,注入当前的DestroyRef。”这样我就可以在组件、指令、服务等的任何地方使用它。

    所以问题是这个文档并没有完全描述注射是如何发生的,还是我有问题?

    (请不要放任何链接来解释这个操作符是如何工作的,我确切地知道它是如何工作并检查了源代码,问题是关于文档理解)

    2 回复  |  直到 2 年前
        1
  •  2
  •   Matthieu Riegler    2 年前

    注入上下文在中进行了解释 this doc 基本上,它是一个运行时上下文,其中设置了当前注入器,Angular能够用于依赖项注入。

    takeUntilDestroyed 需要 DestroyREf 以安排可观察到的完成。这可以通过两种方式实现:

    • 依赖DI来获得它,默认行为和使用 inject(DestroyRef) 。 inject 当然需要注入上下文
    • 通过 DestroyRef 作为参数,因此不需要注入上下文。
        2
  •  0
  •   Andrew Allen    2 年前

    代码中:

    class SomeComponent {
      // this is in an injection context
      someService = inject(SomeService);
      destroyRef = inject(DestroyRef)
    
    
      constructor() {
        // this is in an injection context
    
        obs$.pipe(
          takeUntilDestroyed() // destroyRef not needed
        ).subscribe(() => {
          ...
        })
      }
    
      ngOnInit() {
        // this is NOT in an injection context
      }
    
      someMethod() {
        // this is NOT in an injection context
    
        obs$.pipe(
          takeUntilDestroyed(this.destroyRef) // destroyRef needed
        ).subscribe(() => {
          ...
        })
      }
    }
    
    推荐文章