Rxjs 在所有 http 请求完成时通知每个请求的错误处理

Rxjs notify when all http requests finish with error handling for each request

嗨,我有一些 class 对象到 POST,我需要将结果存储回它们,例如:

class Bid {
    price: number;
    result?: string;
}
const bids: Bid[] = [{price: 10},{price:20}];
for (const bid of bids) {
    http.post(bid).subscribe(
        r => bid.result = r,
        e => bid.result = "error:" + e
    );
}

到目前为止一切顺利,但现在我想在所有 POST 时收到通知 return,就好像我正在分叉所有 POST 并订阅它,然后当他们都完成时做点什么。

与 forkjoin 不同的是我需要在每个 POST 订阅中进行错误处理。

我想知道如何做到这一点,因为我还需要订阅每个 POST 以将结果存储在每个相应的源 class 对象中。

如果我没理解错的话,

的组合
  • tap 将结果存储在每个对象中并管理每个 post
  • 的错误
  • catchError 避免错误传播
  • forkJoin 将 post 粘合在一起

应该可以。

解决方案可能是这样的

class Bid {
    price: number;
    result?: string;
}
const bids: Bid[] = [{price: 10},{price:20}];

const posts = bids.map(bid => {
   return http.post(bid).pipe(
     // taps accepts an Observer as parameter
     tap({
       next: res => bid.result = r,
       error: e => bid.result = "error:" + e
     }),
     // catch the error and return something that signals the error occurence
     catchError(err => of('Error'))
   )
})

forkJoin(posts).subscribe({
   next: data => {// data is an array containing either the result or the error }
   complete: () => console.log('I am Done')
})