首页 > 解决方案 > 如何取消订阅事件订阅

问题描述

我正在使用事件来订阅我的 ionic 3 应用程序中的事件。似乎有两种方法可以取消订阅,如unsubscription1()unsubscription2()

你能告诉这两种方法有什么区别吗?他们都可以按预期取消订阅吗?

import { Events } from 'ionic-angular';
    ...

    messageSubscription: any

    constructor(private events: Events ...){
      ...
    }
    
    subscription(){
      messageSubscription = this.events.subscription("newmessage", () => {
      ...
      }
    }
    
    unsubscription1(){
      this.events.unsubscription("newmessage")
    }
    
    unsubscription2(){
      messageSubscription.unsubscribe()
    }

标签: angularionic-frameworkevents

解决方案


为销毁条件声明一个变量

public destroyed = new Subject();

添加 ngDestroy 生命周期钩子

ngOnDestroy() {
      this.destroyed.next();
      this.destroyed.complete();
    }

并使用 takeUntil()。使用像 takeUntil 这样的操作符而不是手动取消订阅也将完成 observable,触发 observable 上的任何完成事件。

   this.events.
  .pipe(takeUntil(this.destroyed))
   subscription("newmessage", () => {
  ...
  }

推荐阅读