取消订阅 Observable 停止 http 调用
Unsubscribe from Observable stopping the http call
我遇到了一个问题。不确定它是否按预期工作。
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
提前致谢
您不在自己的订阅上使用 add
。这是一个working solution
我没有使用 add
方法,而是简单地将订阅分配给您的 class 成员。
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
要与此一起销毁,因此您可以添加它。
add(teardown: TeardownLogic): Subscription
Adds a tear down to be called during the unsubscribe() of this
Subscription.
有关详细信息,请查看 docs
问题是您在使用 .add()
添加任何订阅之前调用 .unsubscribe()
。
当您调用 .unsubscribe()
时,它将订阅对象标记为 "closed",当您尝试添加任何其他订阅时,它也会取消订阅,因为 "parent" 订阅是 "closed" 已经。
所以您不会看到任何控制台输出,因为 timer()
是异步发出的,实际上您甚至在它发出任何东西之前就取消订阅了。相反,startWith
运算符在订阅时立即发出。
这些是特定的行
我遇到了一个问题。不确定它是否按预期工作。
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
提前致谢
您不在自己的订阅上使用 add
。这是一个working solution
我没有使用 add
方法,而是简单地将订阅分配给您的 class 成员。
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
要与此一起销毁,因此您可以添加它。
add(teardown: TeardownLogic): Subscription
Adds a tear down to be called during the unsubscribe() of this Subscription.
有关详细信息,请查看 docs
问题是您在使用 .add()
添加任何订阅之前调用 .unsubscribe()
。
当您调用 .unsubscribe()
时,它将订阅对象标记为 "closed",当您尝试添加任何其他订阅时,它也会取消订阅,因为 "parent" 订阅是 "closed" 已经。
所以您不会看到任何控制台输出,因为 timer()
是异步发出的,实际上您甚至在它发出任何东西之前就取消订阅了。相反,startWith
运算符在订阅时立即发出。
这些是特定的行