![](/img/trans.png)
[英]How to get selected object from valueChanges but only bind object id to form using Angular reactive forms?
[英]How to unsubscribe from valueChanges in Angular 4 reactive forms?
我正在 Angular 4 中制作一個反應形式,並在如下形式中尋找valueChanges
:
this.searchForm.valueChanges.subscribe((value) => {
console.log(value);
});
上面的代碼完美運行。 但是如何取消訂閱ngOnDestroy()
上的valueChanges
,因為this.searchForm.valueChanges.unsubscribe()
似乎不起作用。 請幫我解決這個問題。
subscribe
返回一個Subscription類型的對象,您可以從中unsubscribe
this.subscription = this.searchForm.valueChanges.subscribe((value) => {
console.log(value);
});
...
ngOnDestroy() {
this.subscription.unsubscribe();
}
@Suren 有正確的答案,我只想添加一些我在訂閱很多時使用的代碼。
...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
console.log(value);
}));
...
private subscriptions: Subscription[] = [];
ngOnDestroy(): void {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
})
}
我創建了訂閱處理程序類
import { OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';
export class SubscriptionDisposer implements OnDestroy {
protected ngUnsubscribe: Subject<void> = new Subject<void>();
constructor() {
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
那么你需要通過 SubscriptionDisposer 擴展你的組件類你的代碼看起來像
this.searchForm.valueChanges
.takeUntil(this.ngUnsubscribe)
.subscribe((value) => {
console.log(value);
});
這篇文章有正確的解決方案。 在少數情況下不起作用,因為可能有多個訂閱。
您必須檢查所有訂閱並確保您取消訂閱所有訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.