[英]Argument when using .next() with takeUntil
I've noticed recently after upgrading my rxjs version that you can't use the .next()
method this.ngUnsubscribe$.next();
我最近注意到在升级我的 rxjs 版本后你不能使用
.next()
方法this.ngUnsubscribe$.next();
as it is anymore as you would below:就像你在下面一样:
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();
}
}
But now you must send an argument to it like this:但是现在你必须像这样向它发送一个参数:
this.ngUnsubscribe$.next(null);
or或者
this.ngUnsubscribe$.next(true);
My question is why?我的问题是为什么? And what value would you know to send?
您知道要发送什么价值?
You're defining your Subject as Subject<void>
.您将 Subject 定义为
Subject<void>
。 Calling next()
wants to emit undefined
.调用
next()
想要发出undefined
。
So you should call this.ngUnsubscribe$.next(void 0)
instead.所以你应该调用
this.ngUnsubscribe$.next(void 0)
来代替。
This happens after upgrading rxjs version to 7 from 6将 rxjs 版本从 6 升级到 7 后会发生这种情况
Rxjs 7 changes Rxjs 7 变化
After checking the changelog and several github issues about this situation,在检查了关于这种情况的变更日志和几个github问题后,
Subject: resolve issue where Subject constructor errantly allowed an argument (#5476) (e1d35dc)
主题:解决主题构造函数错误地允许参数的问题 (#5476) (e1d35dc)
Subject: no default generic (e678e81)
主题:没有默认泛型 (e678e81)
Changelog 7.0.0-beta.1 and the commit where empty value is removed from the tests 变更日志 7.0.0-beta.1和从测试中删除空值的提交
I realized that the solution was to either provide a value or simply typecast the Subject
with <void>
(as @martin also said) as in destroy$ = new Subject<void>()
if you want to next
it with an empty value.我意识到解决方案是要么提供一个值,要么简单地用
<void>
(正如@martin也说过的)对Subject
进行类型转换,如destroy$ = new Subject<void>()
如果你想用一个空值next
它。
Another approach to fix this would be to use the ng-neat npm package: https://github.com/ngneat/until-destroy解决此问题的另一种方法是使用 ng-neat npm package: https://github.com/ngneat/until-destroy
Just by adding @UntilDestroy({ checkProperties: true })
to the top of your class you can remove all the takeUntils(this.unsubscribe) out of the code and remove the ngOnDestroy method.只需将
@UntilDestroy({ checkProperties: true })
添加到 class 的顶部,您就可以从代码中删除所有 takeUntils(this.unsubscribe) 并删除 ngOnDestroy 方法。 Just think it looks a lot cleaner and you will have less imports.只是认为它看起来更干净,你将有更少的进口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.