-1

I implement a call in the ngOnInit to two api route to get some data, I'm using angular 7 and implement forkJoin to call the api like that :

  ngOnInit() {
    debugger
    this.route.params.pipe(
      switchMap(params => forkJoin([
        this.http.get('/api/surveys/' + params.id),
        this.http.get('/api/surveys/getStatistics/' + params.id)
      ]))
    ).subscribe(result => {
      this.survey = result[0];
      this.statistics = result[1];
      this.updateChart(result[1]);
    }, 
      error => this.handleError(error)
    );
  }

private handleError(error) {
  debugger
  if (error.status === 400) {
    this.showError(error.error.error, 'Erreur!');
    if (error.error.error === 'Le sondage demandé n\'existe plus!') {
      this.router.navigateByUrl('/sondage');
    }
  }
}

private updateChart(statistics) {
  debugger
  statistics.options.forEach(option => {
    this.pieData.push(option.number);
    option.color = this.d3Colors[this.colorCounter];
    this.colorCounter = this.colorCounter + 1;
  });  
}

after the first debugger the code does not run the call request to the API and pass directly to handleError funcion ! and generate a 500 server error

547n00n
  • 1,356
  • 6
  • 30
  • 55

1 Answers1

0

500 is generally error thrown from API server itself. If your design permits, you should separate both API calls. This way failure of first call will not impact second call.

From forkJoin specs: "If any input observable errors at some point, forkJoin will error as well and all other observables will be immediately unsubscribed."

So failure of one call makes other API call success irrelevant as observable is already unsubscribed.

Don
  • 1,334
  • 1
  • 10
  • 18
  • Saying they “should” separate the calls is suspect. Why would OP be calling unneeded data into the view? If the view requires all data, the entire view should fail and not render a partial view. If the views can exist separately, then they should be separate views calling the data they require. But general best practice is to call all of your view data in one stream and have it fail or succeed as a unit – bryan60 Mar 04 '20 at 16:23
  • Also, if individual error handling is required, then each individual request can have its own `catchError` in its own pipe. – Kurt Hamilton Mar 04 '20 at 16:26