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.

5
  • 1
    you mean display error for each request? Commented Oct 10, 2017 at 11:52
  • 2
    Possible duplicate of angular2 rxjs observable forkjoin Commented Oct 10, 2017 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. Commented Oct 10, 2017 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. Commented Oct 10, 2017 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. Commented Oct 10, 2017 at 14:08

1 Answer 1

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 ...
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.