Angular 5应用中无法取消订阅BehaviorSubject问题求助
解决Angular 5中BehaviorSubject订阅无法在ngOnDestroy取消的问题
嘿,我来帮你搞定这个订阅取消的问题!你现在踩了个很容易犯的小语法错误,导致takeWhile根本没法正确判断是否要停止订阅。
先看你的代码里的关键问题:
.takeWhile(() => this.alive = true)
这里你用的是赋值运算符=,而不是比较运算符===!每次执行这个判断时,都会把this.alive强制设为true,所以takeWhile永远认为条件成立,订阅自然不会被终止。
修正方案一:修复takeWhile的判断逻辑
- 先在组件类里初始化标志位:
private alive = true;
- 把
takeWhile里的赋值改成比较:
getConfirmReturnValue() { this.confirmService.getReturnValue() .takeWhile(() => this.alive === true) // 这里改成===,判断alive的当前值 .subscribe( suc => { console.log('return value::', suc); if (suc != 0 && suc.hasOwnProperty('returnValue')) { this.deleteLanguage(suc); } }); }
- 在
ngOnDestroy里切换标志位:
ngOnDestroy() { this.alive = false; }
这样当组件销毁时,alive变成false,下一次takeWhile判断就会终止订阅啦。
方案二:用Subscription手动管理订阅
如果你的组件里只有这一个订阅,或者想更精准地控制单个订阅,也可以用RxJS的Subscription对象:
- 先在组件里定义一个订阅变量:
private confirmSubscription: Subscription;
- 订阅时把返回值赋值给这个变量:
getConfirmReturnValue() { this.confirmSubscription = this.confirmService.getReturnValue() .subscribe( suc => { console.log('return value::', suc); if (suc != 0 && suc.hasOwnProperty('returnValue')) { this.deleteLanguage(suc); } }); }
- 在
ngOnDestroy里手动取消订阅:
ngOnDestroy() { if (this.confirmSubscription) { this.confirmSubscription.unsubscribe(); } }
这种方式更直接,适合单个订阅的场景,避免标志位管理可能带来的其他问题。
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

