Home > OS >  How to read response code from httpClient POST in angular 13
How to read response code from httpClient POST in angular 13

Time:07-17

My backend is only answering an "OK" with 201 code. Well, I want to read this 201 code from angular but I'm only able to read the response body: "OK". This is the code of the subscription:

this.socialService.postComment(this.contentCode, comment, this.answeredComment.id).subscribe(
      value => {
        console.log(value);
        console.log(value.status);
        console.log(value.headers);
        console.log(value.body);
      }
    );

As you can see, I'm trying to read the status code in many ways but all of them print in console undefined but the first one, which print "OK". This is the postComment code:

postComment(contentCode: number, comment: string, answeredComment: number): Observable<HttpResponse<string>> {
    
    let params = new HttpParams();
    params = params.append('contentCode', contentCode.toString());
    if(answeredComment != null){
      params = params.append('answer_to', answeredComment.toString());
    }
    const httpOptions = { 
      headers: new HttpHeaders({ 
        'Content-Type': 'application/json'
      }), 
      params: params,
      comment: comment,
      observe: 'response'
    };
    return this.httpClient.post<any>(`${environment.apiBase}/social/comments/postcomment/`, httpOptions);
  }

I think I'm doing something wrong. How can I read the response code?

CodePudding user response:

It is not clear what exactly you want to achieve.

  • What is the expected response body? Empty? An object? If so, what type?
  • Do you want to check the statusCode of the response before doing something with the response? If so, what do you want to do after checking the reponseCode?
  • What should be the responseType of the Oservable?
  • Do you want to catch http error codes?
  • Do you want to just return the statusCode?

You are using post() incorrectly because you are adding comment in your httpOptions, read more about it here. In this solution, I will return the statusCode of the response. With this example, you should be able to implement other scenarios.

postComment(
  contentCode: number,
  comment: string,
  answeredComment: number | null
): Observable<number> {
  return this.http
    .post(`${environment.apiBase}/social/comments/postcomment/`, comment, {
      headers: { 'Content-Type': 'application/json' },
      params: {
        contentCode: contentCode.toString(),
        ...(answeredComment !== null && {
          answered_to: answeredComment.toString(),
        }),
      },
      observe: 'response',
    })
    .pipe(
      map((response) => {
        return response.status;
      })
    );
}

CodePudding user response:

You are doing a post request and missing data, you should change it to get request or pass it some data. You can simply try to change this:

const data = {};
return this.httpClient.post<any>(`${environment.apiBase}/social/comments/postcomment/`, data, httpOptions);

CodePudding user response:

If the POST call produces "201 OK" response, its OK.

Then, I might setup another GET call to the server to check if that ID has been created/updated.

If, yes, then I will need to get the record returned by GET, and implement in my front-end. Otherwise, If your BACKEND is yours, you can implement further information to give you more messages.

Check below code, which I mostly use for my own purposes, only

 // set response code - 400 bad request
http_response_code(400);

// tell the user
echo json_encode(array(
    'passed' => true,
    'Response' => "400 bad request" . "<br>" .
         " !empty(" . "$" . "data->FIELD NAME) is NOT successful."  . "<br>" .
        " Chances are that user has entered Bad Data.",
    'userMessage' => "User creation failed. Please check your data, or try again later or just send message to helpline for support."
));
  • Related