[英]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.