Search code examples
angularrxjsangular2-servicesfork-join

Angular 2/4 Error handling in forkjoin url


I am usimg angular 2 and i am using forkjoin for one of the scenario where i have to execute multiple rest calls in parallel.Following is my function

 private getBatchObservableData(data: Array<Widget>): Observable<any> {
    let observableBatch = [];
    data.forEach(widget => {
      observableBatch.push(this._http.get(widget.apiPath).delay(500).map((data) => data.json()).share())
    });
    return Observable.forkJoin(observableBatch);
  }

This is working perfectly fine.But when any one of the rest call fails the wholeforkjoin fails.So is there any way to emit values of those rest calls and just log which failed. ?? Please help.


Solution

  • If you use catch to prevent errors bubbling up to the forkJoin call, you can re-emit them as values and can inspect the values in forkJoin's optional project function:

    private getBatchObservableData(data: Array<Widget>): Observable<any> {
      let observableBatch = [];
      data.forEach(widget => observableBatch.push(this._http
        .get(widget.apiPath)
        .delay(500)
        .map(data => data.json())
        .catch(error => Observable.of(error))
      ));
      return Observable.forkJoin(observableBatch,
        (...results) => ({
          failed: results.map(r => r instanceof Error ? r : null),
          succeeded: results.map(r => r instanceof Error ? null : r)
        })
      );
    }
    

    The above example will emit an object containing two arrays, each will contain the same number of elements as the data array:

    • the elements in failed will contain an Error if the corresponding request failed and null otherwise.
    • the elements in succeeded will contain the data if the corresponding request succeeded and null otherwise.

    It should be easy to re-arrange things if you need to do things a little differently.