我尝试在 angular2 组件中使用 rxjs observable 设置超时函数
this._subscription = Observable.timer(1000).subscribe(() => {
console.log('inside timeout')
})
并以其他方式退订。然而,可观察的从未执行过 如果我改成
let _subscription = Observable.timer(1000).subscribe(() => {
console.log('inside timeout')
})
它工作正常。我也试过
this._subscription=setTimeout(()=>{},1000)
同样的事情发生了。我怀疑这是 ngZone 错误,所以我将函数包装在
this._ngZone.runOutsideAngular(() => {})
但结果是一样的。有人遇到过同样的问题吗?我正在使用 Angular 2.2.4
最佳答案
订阅一个 observable 应该在 ngOnInit
方法中完成(在大多数情况下)。
所以现在,如果你想退订它,你可以这样做:
private onDestroy$ = new Subject<void>();
private stopObs$ = new Subject<void>();
ngOnInit() {
someObs$
// stop the observable if the component is being destroyed
.takeUntil(this.onDestroy$)
// stop the component from another method if you want
.takeUntil(this.stopObs$)
.do(x => console.log(`A value has been received: ${x}`))
.subscribe();
}
callThisMethodToStopListeningToObs() {
this.stopObs$.next();
this.stopObs$.complete();
}
ngOnDestroy() {
this.onDestroy$.next();
this.onDestroy$.complete();
}
这里的 someObs$
可能是一个 interval
,一个 timer
或任何可观察的 :)。
关于javascript - 分配给组件属性时不执行订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46824960/