【问题标题】:Convert failing Observable into a good one将失败的 Observable 转换为好的 Observable
【发布时间】:2019-04-03 11:46:26
【问题描述】:

我调用了一个返回 observable 的 HTTP 服务(它是第三方库的一部分,因此我无法更改其内部代码),并且它在订阅我想要处理的用例时抛出错误在幸福的道路上。

我有这样的事情:

我的服务等级:

class MyService {
  getEntities(): Observable<any> {
    return this.http.get('<the url'>)
      .pipe(
        catchError(err => {
          // Handle the errors and returns a string corresponding to each message.
          // Here I show an example with the status code 403
          if (err.status === 403) {
            return throwError('My error message for 403');
          }

          // This is what I want to do.
          if (err.status === 409) {
            // Somehow, make this to trigger the goodResponse in the consumer class.
          }
        })
      );
  }
}

我的消费者:

class MyComponent {
  private myService: MyService;

  constructor() {
    this.myService = new MyService();
  }

  callTheAPI() {
    this.myService.getEntities()
      .subscribe(goodResponse => {
        // Handle good response
      }, error => {
        // Handle error
      });
  }
}

所以,对于当前的代码示例,我要做的是,对于状态码为409的情况,订阅成功。

【问题讨论】:

    标签: typescript rxjs rxjs6 rxjs-pipeable-operators rxjs-lettable-operators


    【解决方案1】:

    然后返回一个新的 Observable(发送 next 项目)。 throwError 仅发送error 通知,因此您可以使用of()

    import { of } from 'rxjs';
    
    ...
    
    catchError(err => {
        // Handle the errors and returns a string corresponding to each message.
        // Here I show an example with the status code 403
        if (err.status === 403) {
            return throwError('My error message for 403');
        }
    
        // This is what I want to do.
        if (err.status === 409) {
            return of(/* fake response goes here */)
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2018-10-23
      • 2021-10-27
      • 2023-03-23
      • 2021-12-02
      相关资源
      最近更新 更多