2

Here is my Setup, i have a Angular reactive form which posts Data to a RestAPI to make this happen there is multiple files involved. First one is the apiService where i call the folowing code

  post(config: {endpoint: string, useAuthUrl?: boolean, body: any, params?: any, reqOpts?: any}) {
      config = ApiService.initRequestOptionsAndParams(config);
      return this.http.post(this.apiUrl(config.useAuthUrl) + config.endpoint, config.body, config.reqOpts);
  }

this file is called by my surveyService file via

  quickCreate(survey: Partial<ISurvey>) {
        return this.api.post({endpoint: '/survey', body: survey});
    }

and finally i call this from my surveyrequest via

 this.surveyRequestService.quickCreate(this.form.value)
      .subscribe(response => {
        console.log('HTTP Response: ' + JSON.stringify(response));
      });

there is some more as i intercept the http request and add the x-token as header but that's not of issue here. My problem is all works fine as long as the far end response with a 200 or so, if i get a 400 or 500 the response never makes it into the response but i get the error in console.

enter image description here

So how can i access this error in my code to check if my post was successful and if not what the error was.

1 Answer 1

2

You can pass another function in surveyrequest where you are subscribing to the actual observable.

 this.surveyRequestService.quickCreate(this.form.value)
      .subscribe(response => {
        console.log('HTTP Response: ' + JSON.stringify(response));
      },
      (error) => {
        if(error instanceof HttpErroResponse) {
           // Handle error
           console.log("Status: "+ error.status +", Message: " + error.message);
        }
      });

Also, Check this to see how to handle errors using HttpInterceptor.

HTH.

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.