【问题标题】:Unsubscribe not working on subscription interval in Typescript取消订阅在 Typescript 中的订阅间隔上不起作用
【发布时间】:2019-09-26 19:49:11
【问题描述】:

我正在订阅一个间隔,如果出现错误,应该取消订阅该间隔。同样在 ngDestroy 上它应该取消描述。但是,当我转到我网站上的另一个组件时,我仍然可以看到它轮询服务器的位置。

使用 rxjs 6.2.1

这是我的代码

private polling: Subscription;

ngOnDestroy() {
    if(this.polling){    
    this.polling.unsubscribe();
    }
  }

 loadContacts(){
    this.polling = interval(10000)
                .subscribe((val) => {
                  this.resourceService.getQueryUserPresence(this.contacts[0].Email).subscribe((response) => {
                    console.log('polling for ' + fullName);                    
                  }, (error: any)=> {
                    console.log('Error Getting Status:  ' + error)
                    if(this.polling){
                      this.polling.unsubscribe();
                      }
                  });
                }, (error: any)=> {
                  console.log('Error polling:  ' + error)
                  if(this.polling){
                    this.polling.unsubscribe();
                    }
                })
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    据我从SO post 了解到的,在 observable 抛出错误完成之后,不需要取消订阅。

    我认为您的代码中的错误是您在 第一个订阅处理程序中订阅了该请求,这就是您在 第二个中看不到错误的原因回调

    就像有这样的东西:

    interval(1000)
     .subscribe(
      () => {}, 
      () => { console.log('I will never be able to catch an error just from an observable that emits values at certain interval!') }
    )
    

    解决此问题的一种方法是将您的 API 调用置于 pipeable operator 中,例如 switchMapmergeMapexhaustMapconcatMap,具体取决于您的用例。 (上述运算符也称为high-order operators)。

    this.polling = interval(1000)
     .pipe(
      mergeMap(() => this.resourceService.getQueryUserPresence(this.contacts[0].Email))
     )
     .subscribe(
      response => console.log('polling operation successful!', response),
      err => console.log('error caught from the API call!', err)
     )
    

    编辑

    开始轮询,但仅在 this.contacts.length > 0 时才进入 webAPI 调用

    我认为你可以使用skipWhile 运算符。

    this.polling = interval(1000)
     .pipe(
      skipWhile(() => this.contacts.length === 0),
      mergeMap(() => this.resourceService.getQueryUserPresence(this.contacts[0].Email))
     )
     .subscribe(
      response => console.log('polling operation successful!', response),
      err => console.log('error caught from the API call!', err)
     )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多