1

我仍在学习 RxJs,我正在尝试使用 concatMap() 来不使用嵌套订阅。我希望运行第一个调用,然后延迟一两秒(在第二个请求之前创建数据库记录),然后再运行第二个请求。我还想专门为每个请求添加错误处理,以便我可以单独为它们捕获错误。

到目前为止,我有一些运行请求 1、延迟,然后运行请求 2 的东西。

return this.request_1(postData).pipe(
      concatMap(res => of(res).pipe( delay( 2000 ) )),
      concatMap(res => this.request_2(parseInt(data.id), parseInt(model['_id'])) )
    );

我想知道的是——

  1. 我可以在每个请求上使用诸如 catchError() 之类的东西吗?
  2. 如果我希望请求 1 在第二个请求运行之前完成,这是正确的吗?

谢谢!

4

1 回答 1

1

您可以在catchError每个请求中添加一个。但只要你不想改变错误对象,我宁愿只catchError在管道末端有一个。这只是将每个错误都冒泡给订阅者。

然后可以在订阅中完成错误处理本身

const source = of('World').pipe(
  concatMap(res => of(res).pipe(
    delay(2000),
    map(res => res += ' + concat 1')
  )),
  concatMap(res => of(res).pipe(
    map(res => res.h += ' + concat 2')
  )),
  catchError(err => throwError(err))
);

source.subscribe(
  x => console.log(x),
  error => console.log('error', error)
);

https://stackblitz.com/edit/rxjs-6dign7

于 2019-03-02T11:44:42.717 回答