繁体   English   中英

将.next() 与 takeUntil 一起使用时的参数

[英]Argument when using .next() with takeUntil

我最近注意到在升级我的 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);

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

您将 Subject 定义为Subject<void> 调用next()想要发出undefined

所以你应该调用this.ngUnsubscribe$.next(void 0)来代替。

将 rxjs 版本从 6 升级到 7 后会发生这种情况

Rxjs 7 变化

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

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

主题:没有默认泛型 (e678e81)

变更日志 7.0.0-beta.1从测试中删除空值的提交

在此处输入图片说明

我意识到解决方案是要么提供一个值,要么简单地用<void> (正如@martin也说过的)对Subject进行类型转换,如destroy$ = new Subject<void>()如果你想用一个空值next它。

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

只需将@UntilDestroy({ checkProperties: true })添加到 class 的顶部,您就可以从代码中删除所有 takeUntils(this.unsubscribe) 并删除 ngOnDestroy 方法。 只是认为它看起来更干净,你将有更少的进口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM