3

I am using Angular 2 HTTP, and have a component subscribing to the response. However, when there is an error, the catch method does not return the error to the subscribed component. It just throws it in the console.

 saveFinalize(fcData: LastForecastInterface) {
    let responseData = JSON.stringify(fcData);
    let body = responseData;

    const headers = new Headers();
    headers.append('Content-Type', 'application/json;charset=UTF-8');

    return this.http.post('/saveFinalize', body, { headers: headers })
      .map((data: Response) => data.json())
      .catch(this.handleError);
}

public handleError(error: Response | any) {
    console.log('err: ', error)
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    // return Observable.throw(errMsg);
    return errMsg;
}

And my subscribed component does not get back a response

saveFinalize() {
  this.loadingData = true;
  return this.httpService.saveFinalize(this.getFc.fcData)
    .subscribe(response => {
        this.loadingData = false;
        console.log(response);
        let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
        let respType = response.success ? 'success' : 'danger';
        this.alertSvc.showAlert(saveResponse, respType);
    });
}

1

2 Answers 2

10

See this code here: (It is from https://angular.io/docs/ts/latest/guide/server-communication.html)

getHeroes() {
  this.heroService.getHeroes()
                  .subscribe(
                    heroes => this.heroes = heroes,
                    error =>  this.errorMessage = <any>error);
}

Notice there are 2 arguments for .subscribe() method. One is the response which you use, and the next one is the error. In order to pass the error to the subscribed component you must use the later argument, which will make your code looks like this:

  return this.httpService.saveFinalize(this.getFc.fcData).subscribe(response => {
    this.loadingData = false;
    console.log(response);
    let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
    let respType = response.success ? 'success' : 'danger';
    this.alertSvc.showAlert(saveResponse, respType);
  }, error => {
    // the errorMessage will be passed here in this "error" variable
  });

When the subscribed method returns a successful response, you will only get your response. But when the subscribed method throws an error you won't get your response, you will only get the error (which is the second argument of the subscribe() method).

You also need to throw the error from the handleError() method. So instead of only return the string value (return errMsg;), you should use return Observable.throw(errMsg);.

Sign up to request clarification or add additional context in comments.

1 Comment

@ahrobins I'm glad to be of help :)
0

You can do

.catch((response: Response) => {
                return Observable.of(response);
            });

which will return the response for you.

1 Comment

This did not work for me, but the answer above from samAlvin did. Thank you, though, for the quick response.

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.