简体   繁体   English

如何取消订阅 Angular 4 反应形式的 valueChanges?

[英]How to unsubscribe from valueChanges in Angular 4 reactive forms?

I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:我正在 Angular 4 中制作一个反应形式,并在如下形式中寻找valueChanges

this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

The above code works perfectly.上面的代码完美运行。 But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work.但是如何取消订阅ngOnDestroy()上的valueChanges ,因为this.searchForm.valueChanges.unsubscribe()似乎不起作用。 Please help me solve this.请帮我解决这个问题。

subscribe returns an object of type Subscription from which you can unsubscribe subscribe返回一个Subscription类型的对象,您可以从中unsubscribe

this.subscription = this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}

@Suren has the right answer, I would just like to add some code I use when I have many subscriptions. @Suren 有正确的答案,我只想添加一些我在订阅很多时使用的代码。

...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
}));
...

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}

I created Subscription disposer class我创建了订阅处理程序类

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();
  }
}

then you need to extend your component class by SubscriptionDisposer Your code will look like那么你需要通过 SubscriptionDisposer 扩展你的组件类你的代码看起来像

this.searchForm.valueChanges
.takeUntil(this.ngUnsubscribe)
.subscribe((value) => {
   console.log(value);
});

This post has the right solution.这篇文章有正确的解决方案。 In a few cases is not working because there could be multiple subscriptions.在少数情况下不起作用,因为可能有多个订阅。

You have to check all subscriptions and ensure that you are unsubscribing from all of them.您必须检查所有订阅并确保您取消订阅所有订阅。

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

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