Search code examples
angularrxjsobservablerxjs-observablesrxjs-pipeable-operators

Is there any alternative rxjs operator for forkJoin to handle individual errors?


I am working on RxJS version 7 in my Angular project. I know that the forkJoin operator will wait for all the observables to complete and then it will emit the values. If any one of them fails, then we get none of the other values as well. But if I want the other values even if one of them fails, then I need to attach a error handler to each of the observables(or api calls) as follows:

forkJoin(
      {
        countries: this.http.get('https://restcountries.com/v2/all').pipe(catchError(error => of(error))),
        products: this.http.get('https://fakestoreapi.com/ppp').pipe(catchError(error => of(error))),
        users: this.http.get('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8').pipe(catchError(error => of(error)))
      }
    ).subscribe((res)=>{
      console.log(res);
    });

So, in this case, even if one of them fails, at least I get the values from the other two api calls. That is totally fine. I am happy with it. But, for example, I have 50 api calls. It is too tedious to attach error handlers to each api call. Is there any alternate RxJS operator to achieve the above behaviour. Please let me know if I can achieve the same behaviour in a better way. Thanks in advance.


Solution

  • just create api wrapper and use it

    public getApi(url: string): Observable<any>{
        return this.http.get(url).pipe(catchError(error => of(error)))
    }
    
    forkJoin(
          {
            countries: this.getApi('https://restcountries.com/v2/all'),
            products: this.getApi('https://fakestoreapi.com/ppp'),
            users: this.getApi('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8')
          }
        ).subscribe((res)=>{
          console.log(res);
        });