取消订阅Observable停止http调用

问题描述 投票:0回答:2

我面临着一个问题。不确定它是否按预期工作。

  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

提前致谢

angular rxjs rxjs6
2个回答
2
投票

问题是你在使用.unsubscribe()添加任何订阅之前调用.add()

当您调用.unsubscribe()时,它将Subscription对象标记为“已关闭”,当您尝试添加任何其他订阅时,它也会取消订阅,因为“父”订阅已经“关闭”。

因此,您将看不到任何控制台输出,因为timer()异步发出,实际上您在发出任何内容之前取消订阅。相比之下,startWith运营商在订阅时立即发布。

这些是特定的行


1
投票

您不会在订阅时使用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,将在订阅被销毁时使用。例如,你可能有其他Subscriptions被这个摧毁,所以你可以添加它。

add(拆解:TeardownLogic):订阅

添加拆除以在本订阅的取消订阅()期间调用。

有关更多信息,请查看docs

© www.soinside.com 2019 - 2024. All rights reserved.