如何退订Angular 4反应形式的valueChanges?

sta*_*ght 2 typescript angular angular4-forms

我在Angular 4中制作了一个反应形式,并valueChanges在下面的形式中寻找:

this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});
Run Code Online (Sandbox Code Playgroud)

上面的代码工作完美。但如何从取消valueChangesngOnDestroy()作为this.searchForm.valueChanges.unsubscribe()似乎并不工作。请帮我解决这个问题。

Sur*_*yan 12

subscribe返回Subscription类型的对象,您可以从中unsubscribe

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

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)


Ven*_*omy 7

@Suren 有正确的答案,我只想添加一些我在订阅很多时使用的代码。

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

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我创建了订阅处理程序类

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

那么你需要通过 SubscriptionDisposer 扩展你的组件类你的代码将如下所示

this.searchForm.valueChanges
.takeUntil(this.ngUnsubscribe)
.subscribe((value) => {
   console.log(value);
});
Run Code Online (Sandbox Code Playgroud)