【问题标题】:Subscription inside the error function handling from outer subscription来自外部订阅的错误函数处理内的订阅
【发布时间】:2020-03-26 22:59:27
【问题描述】:

我有一个在另一个订阅中订阅的案例,我们知道这很糟糕。问题是我不知道如何在这里解决它:

this.backendService.doSomething().subscribe(
  () => { },
  err => {
    this.someService.showOkMessage('title', 'you got an error')
      .subscribe(); // The bad guy
  },
  () => {
    // should not be called if there is an error
    this.someService.showOkMessage('title', 'everything is fine')
      .subscribe(); // Another bad guy
  }
}

我尝试过这样的事情:

this.backendService.doSomething().pipe(
  catchError(errMsg => {
    return someService.showOkMessage('title', 'you got an error').map(() => true));
  )},
  switchMap(isError =>
    if(!isError) return someService.showOkMessage('title', 'everything is fine');
  )
).subscribe();

这可行,但感觉不对,我不想转换/更改流,它应该结束。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    只需要重新排序,当有错误时它会跳到catchError() 如果没有出错,它将运行switchMap

    this.backendService.doSomething().pipe(
      switchMap(()=> someService.showOkMessage('title', 'everything is fine')),
      catchError(errMsg => 
        someService.showOkMessage('title', 'you got an error')
      ),
    ).subscribe();
    

    【讨论】:

    • 哦,有点以为它仍然会通过 switchMap,即使出现错误...这行得通,谢谢!
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2017-08-08
    • 2017-08-01
    • 2012-09-07
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多