【问题标题】:How to unsubscribe from valueChanges in Angular 4 reactive forms?如何取消订阅 Angular 4 反应表单中的 valueChanges?
【发布时间】:2026-02-03 00:20:03
【问题描述】:

我正在 Angular 4 中制作一个响应式表单,并以如下形式查找 valueChanges

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

上面的代码完美运行。但是如何从ngOnDestroy() 上的valueChanges 退订为this.searchForm.valueChanges.unsubscribe() 似乎不起作用。请帮我解决这个问题。

【问题讨论】:

    标签: angular typescript angular4-forms


    【解决方案1】:

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

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

    【讨论】:

    • 这是正确的解决方案。您必须检查所有订阅并确保您取消了所有订阅。
    【解决方案2】:

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

    ...
    this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
       console.log(value);
    }));
    ...
    
    private subscriptions: Subscription[] = [];
    
    ngOnDestroy(): void {
        this.subscriptions.forEach((sub) => {
            sub.unsubscribe();
        })
    }
    

    【讨论】:

    • 我没有意识到subscribe 方法实际上有一个返回值。这是很棒的东西!
    【解决方案3】:

    我创建了订阅处理器类

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

    【讨论】:

      【解决方案4】:

      这篇文章有正确的解决方案。 在少数情况下无法正常工作,因为可能有多个订阅。

      您必须检查所有订阅并确保您取消了所有订阅。

      【讨论】: