Search code examples
angularangular-httpclient

How to read response code from httpClient POST in angular 13


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?


Solution

  • 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;
          })
        );
    }