我面临着一个问题。不确定它是否按预期工作。
startTimerSubscription(){
this.timerSubscription.unsubscribe();
let subscription = this._testService.getTimerData().subscribe((response) => {
console.log(response);
});
this.timerSubscription.add(subscription);
}
每当我调用该函数时,数据永远不会被订阅。即没有控制台打印数据。
我的测试服务有getTimerData()
定义为:
getTimerData(){
return timer(0,10000).pipe(switchMap(()=> {
return of(this.testData);
}));
}
有人可以向我解释这种行为吗?我在订阅之前取消订阅数据。不应该每10秒记录一次数据吗?
我尝试使用interval
运算符,结果是一样的。
我也创造了一个stackblitz example
提前致谢
问题是你在使用.unsubscribe()
添加任何订阅之前调用.add()
。
当您调用.unsubscribe()
时,它将Subscription对象标记为“已关闭”,当您尝试添加任何其他订阅时,它也会取消订阅,因为“父”订阅已经“关闭”。
因此,您将看不到任何控制台输出,因为timer()
异步发出,实际上您在发出任何内容之前取消订阅。相比之下,startWith
运营商在订阅时立即发布。
这些是特定的行
您不会在订阅时使用add
。这是一个working solution
我只是将订阅分配给您的班级成员,而不是使用add
方法。
this.timerSubscription.unsubscribe();
this.timerSubscription = this._testService.getTimerData().subscribe((response) => {
console.log(response);
});
------
this.intervalSubscription.unsubscribe();
this.intervalSubscription = this._testService.getIntervalData().subscribe((response) => {
console.log(response);
});
add
方法获取TearDownLogic
,将在订阅被销毁时使用。例如,你可能有其他Subscription
s被这个摧毁,所以你可以添加它。
add(拆解:TeardownLogic):订阅
添加拆除以在本订阅的取消订阅()期间调用。
有关更多信息,请查看docs