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?
It is not clear what exactly you want to achieve.
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;
})
);
}