angular - 如何取消订阅事件订阅
问题描述
我正在使用事件来订阅我的 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()
}
解决方案
为销毁条件声明一个变量
public destroyed = new Subject();
添加 ngDestroy 生命周期钩子
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
并使用 takeUntil()。使用像 takeUntil 这样的操作符而不是手动取消订阅也将完成 observable,触发 observable 上的任何完成事件。
this.events.
.pipe(takeUntil(this.destroyed))
subscription("newmessage", () => {
...
}
推荐阅读
- jenkins - 无法通过通用方法登录时如何登录Jenkins
- maven - 使用 mvn flyway:migrate 的 Flyway 迁移给出“迁移 1.0.53 不匹配”错误
- kubernetes - 使用 terraform 向 EKS 节点添加标签
- react-native - 如何使用带有 React native 的 switch 更改应用程序的按钮颜色
- javascript - 在 React 中搜索时返回“未找到结果”状态
- html - 如何将本地 html 文件转换为包含 gif 图像的 pdf?
- node.js - 如何使用节点在 redis 中获取原始十六进制字符串值?
- android - 如何安装模拟器可执行文件 Visual Studio Android 模拟器
- jquery - 如何将粘贴事件支持添加到magicsuggest?
- json - 根据 Swift 中的最新日期使用 JSON 解码过滤数组中的字典