【问题标题】:Argument when using .next() with takeUntil将 .next() 与 takeUntil 一起使用时的参数
【发布时间】:2021-10-03 04:19:13
【问题描述】:

我最近在升级我的 rxjs 版本后注意到,你不能像下面那样使用 .next() 方法 this.ngUnsubscribe$.next();

export class TakeUntilComponent implements OnDestroy {
  // Our magical observable that will be passed to takeUntil()
  private readonly ngUnsubscribe$: Subject<void> = new Subject<void>();

  // Our subject that we will subscribe to
  subjectA$: Subject<number> = new Subject<number>();

  constructor() {
    this.subjectA$
      .pipe(takeUntil(this.ngUnsubscribe$))
      .subscribe(value => {
      // logic goes here ...
    });
  }

  ngOnDestroy(){
    // Emit a value so that takeUntil will handle the closing of our subscriptions;
    this.ngUnsubscribe$.next();
    // Unsubscribe from our unsubscriber to avoid creating a memory leak
    this.ngUnsubscribe$.unsubscribe();
  }

}

但是现在你必须像这样向它发送一个参数:

this.ngUnsubscribe$.next(null);

this.ngUnsubscribe$.next(true);

我的问题是为什么?您知道要发送什么值?

【问题讨论】:

  • this.ngUnsubscribe$.next(); 会给你一个错误吗?
  • 你使用的是哪个版本的 RxJS?对我来说,它仍然适用于 6.6.0 版
  • 它也应该适用于 rxjs 7 github.com/ReactiveX/rxjs/issues/6324
  • 啊,我正在使用“rxjs”:“^7.2.0”。我得到的错误是:预期有 1 个参数,但得到了 0.ts(2554) Subject.d.ts(31, 10):未提供“值”的参数。 (方法) Subject.next(value: any): void 没有可用的快速修复
  • 为什么显示Subject&lt;any&gt;而不是Subject&lt;void&gt;

标签: angular rxjs


【解决方案1】:

解决此问题的另一种方法是使用 ng-neat npm 包: https://github.com/ngneat/until-destroy

只需将 @UntilDestroy({ checkProperties: true }) 添加到类的顶部,您就可以从代码中删除所有 takeUntils(this.unsubscribe) 并删除 ngOnDestroy 方法。试想一下,它看起来更干净,你的导入也会更少。

【讨论】:

    【解决方案2】:

    这发生在将 rxjs 版本从 6 升级到 7 之后

    Rxjs 7 变化

    在检查了更新日志和关于这种情况的几个 github 问题后,

    主题:解决主题构造函数错误地允许参数的问题 (#5476) (e1d35dc)

    主题:无默认泛型 (e678e81)

    Changelog 7.0.0-beta.1the commit where empty value is removed from the tests

    我意识到解决方案是要么提供一个值,要么简单地将Subject&lt;void&gt; (如@martin 也说过)在destroy$ = new Subject&lt;void&gt;() 中,如果你想next 它带有一个空值.

    我的相关帖子:rxjs 7 update - Subject - Expected 1 arguments, but got 0

    【讨论】:

    • 感谢您的信息 :) 非常有帮助
    【解决方案3】:

    您将主题定义为Subject&lt;void&gt;。调用next() 想要发出undefined

    所以你应该打电话给this.ngUnsubscribe$.next(void 0)

    【讨论】:

    • 这样做与 this.ngUnsubscribe$.next(null); 相比有什么不同吗? ?
    • null 是 TypeScript 中的一种类型,因此根据您的 tsconfig,您需要特别指定变量可以具有 null 类型。所以使用next(null)next(void 0) 是两个不同的调用。
    • 非常感谢。关于为什么仅在升级我的 rxjs 后才发生此错误的任何想法?
    • 他们改变了next()的类型
    • 啊,我明白了,谢谢。升级我项目中的所有软件包时总是很可怕,总是会出现问题。
    猜你喜欢
    • 2017-12-22
    • 2018-12-25
    • 1970-01-01
    • 2021-09-01
    • 2019-11-07
    • 2019-12-17
    • 2020-08-10
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多