angular - 如果没有“订阅”类型的对象,如何取消订阅 Observable?
问题描述
如果我订阅了一个 Observable,如果没有“订阅”类型的对象,我该如何取消订阅?
如果我有类似的东西:
this.subscription = bla ...
然后我可以按如下方式取消订阅(在 ngOnDestroy() 方法中):
this.subscription.unsubscribe();
但是如果我有这样的东西怎么办:
ngOnInit() {
this.isLoggedIn$ = this.authService.isLoggedIn();
this.isLoggedIn$.subscribe(res => {
if (res) {
this.isLoggedIn = true;
}
else {
this.isLoggedIn = false;
}
});
}
我怎样才能取消订阅?我什至必须退订吗?如果不是,为什么不呢?
解决方案
有 3 种方法可以取消订阅 observable
您可以使用上述方法
this.subscription
为每个订阅分配订阅,然后显式取消订阅。(应该避免)您可以通过以下示例使用 takWhile 管道:
private isAlive = true; ngOnInit() { this.isLoggedIn$ = this.authService.isLoggedIn(); this.subscription = this.isLoggedIn$ .pipe(takeWhile(() => this.alive)) .subscribe(res => { if (res) { this.isLoggedIn = true; } else { this.isLoggedIn = false; } }); } ngOnDestroy() { console.log('[takeWhile] ngOnDestory'); this.alive = false; }
使用 takeUntil 运算符:
private unsubscribe: Subject<void> = new Subject(); ngOnInit() { this.isLoggedIn$ = this.authService.isLoggedIn(); this.subscription = this.isLoggedIn$ .pipe(takeUntil(this.unsubscribe)) .subscribe(res => { if (res) { this.isLoggedIn = true; } else { this.isLoggedIn = false; } }); } ngOnDestroy() { this.unsubscribe.next(); this.unsubscribe.complete(); }
我希望这有帮助!
推荐阅读
- c++ - 如何检查矩阵的任何行是否包含所有'A'?
- selenium - 无法通过 :contains() 找到 CSS 选择器
- javascript - 为什么我的算法在这个数字上失败了?
- logging - uwsgi: 错过了 --log-filter 选项
- mysql - 如何使用 sequelize ORM 编写内连接查询?
- pandas - 如何将 CountVectorizer 应用于数据集的列?
- javascript - 在 React Native 中,我有“警告可能未处理的 Promise Rejection (id: 5): TypeError: array.push is not a function”
- mysql - Mysql查询从表中不存在的列表中查找ID
- dapper - 即使我只返回一个对象,我是否必须遍历来自 Dapper 的 IEnumerable 返回?
- javascript - 未捕获的错误:不能将 stdClass 类型的对象用作数组 ---> 第 23 行