![](/img/trans.png)
[英]Angular Observable destroy with takeUntil: What happens when .next() is missing in ngOnDestroy
[英]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)
我意識到解決方案是要么提供一個值,要么簡單地用<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.