我正在使用Angular 5,我正在使用如下的BehaviorSubject(Rxjs版本是" rxjs":" ^ 5.1.0",正如我在package.json文件中提到的那样)
ngOnInit() {
this.getConfirmReturnValue();
}
getConfirmReturnValue() {
this.confirmService.getReturnValue()
.takeWhile(() => this.alive = true)
.subscribe(
suc => {
console.log('return value::', suc);
if (suc != 0 && suc.hasOwnProperty('returnValue')) {
this.deleteLanguage(suc); }
});
}
在onDestroy方法中我取消订阅如下
ngOnDestroy() {
this.alive = false;
}
但我在浏览器控制台中收到以下错误
at SafeSubscriber._next (languages-view.component.ts:143)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:239)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:186)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:126)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:90)
at TakeWhileSubscriber.webpackJsonp.../../../../rxjs/operators/takeWhile.js.TakeWhileSubscriber.nextOrComplete (takeWhile.js:84)
at TakeWhileSubscriber.webpackJsonp.../../../../rxjs/operators/takeWhile.js.TakeWhileSubscriber._next (takeWhile.js:79)
at TakeWhileSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:90)
at BehaviorSubject.webpackJsonp.../../../../rxjs/Subject.js.Subject.next (Subject.js:55)
答案 0 :(得分:1)
takeWhile
运算符的回调函数要求您返回布尔值。现在你正在返回undefined
,因为this.alive = true
只是一个赋值,而这本身并没有返回任何内容。
所以你应该这样做:
.takeWhile(() => this.alive) // or this.alive === true
请注意,仅当takeWhile
发出值时才会调用this.confirmService.getReturnValue()
,因此当组件被销毁时,它可能不会立即意味着链也被处理掉。
答案 1 :(得分:0)
我删除了takeWhile( - )并在下面做了,它解决了我的问题
getConfirmReturnValue() {
this.subscription1 = this.confirmService.getReturnValue()
.subscribe(
suc => {
console.log('return value::', suc);
if (suc != 0 && suc.hasOwnProperty('returnValue')) {
this.deleteLanguage(suc); }
});
}
ngOnDestroy() {
this.subscription1.unsubscribe();
}
答案 2 :(得分:-1)
您可以使用以下代码取消订阅ngOnDestroy。
getConfirmReturnValue() {
this.var = this.confirmService.getReturnValue()
.takeWhile(() => this.alive = true)
.subscribe(
suc => {
console.log('return value::', suc);
if (suc != 0 && suc.hasOwnProperty('returnValue')) {
this.deleteLanguage(suc); }
});}
ngOnDestroy() {
this.var.unsubscribe();}