0

Is it possible to handle errors separately using forkjoin? I need to call multiple requests at the same time, displaying a loading on the screen while the requests are called. If an error occurs in some request, and another success, I need to display the request successfully on the screen, and the error message to the other.

Meu código no Page.ts:

getData(){
   this.loadingService.showLoader("Loading, please wait");

   Observable.forkJoin([
      this.issuesService.getIssues(),
      this.categoryService.getCaretories()
    ]).subscribe(
      (response) => {

        let issues = JSON.parse((response[0] as any)._body);
        let categories = JSON.parse((response[1] as any)._body);

        //do something with issues and categories

      }, (error) => {
        console.log(`Backend returned error was: ${error}`);
        this.closeLoading(refresher);
        this.showContent = false;
      }, () => {
        console.log('complete all request');
        this.closeLoading(refresher);
      });
  }
}

If an error occurs in the Issues request, and in the Category request, return success. I need to display on the screen how to successfully categories, and display an error message for Issues.

Currently, when an error occurs, the error message is displayed for all requests.

Wesley Coetzee
  • 4,768
  • 3
  • 27
  • 45
Erico Souza
  • 276
  • 4
  • 18
  • 1
    you mean display error for each request? – Suraj Rao Oct 10 '17 at 11:52
  • 2
    Possible duplicate of [angular2 rxjs observable forkjoin](https://stackoverflow.com/questions/38048860/angular2-rxjs-observable-forkjoin) – Suraj Rao Oct 10 '17 at 12:29
  • 1
    @SurajRao Not really a dupe since it doesn't explain how errors should be distinguished from real values. But related, yes. – Estus Flask Oct 10 '17 at 12:45
  • @estus both questions ask for the same thing. If you are talking about the _answers_... I suppose you can add your additional info here or in the dupe target. – Suraj Rao Oct 10 '17 at 12:48
  • @SurajRao but the duplicate question don't have 'answers'. And I see the duplicate before, and I tried to solve it as they suggested, but it did not work. – Erico Souza Oct 10 '17 at 14:08

1 Answers1

4

RxJS forkJoin works similarly to Promise.all. If one of the sources throws an error, the resulting source also throws. If it shouldn't throw, the error should be caught in a source where it is thrown:

Observable.forkJoin(
  this.issuesService.getIssues().catch(err => Observable.of(err)),
  this.categoryService.getCaretories().catch(err => Observable.of(err))
)

Then errors can be handled like regular values:

  .subscribe(([issuesRes, categoriesRes]) => {
    if (issuesRes instanceof Error) ...
    else ...
  });
Estus Flask
  • 206,104
  • 70
  • 425
  • 565