Angular 13中如何从HttpClient POST请求读取响应状态码
解决Angular 13中无法读取响应状态码的问题
你的问题根源在于HttpClient.post方法的参数传递错误,导致observe: 'response'配置未生效,因此订阅时只能获取响应体而非完整的HttpResponse对象。
错误分析
在你的postComment方法中,你将包含comment和observe: 'response'的对象作为第二个参数传给了post方法,但Angular的HttpClient.post签名是:
post(url: string, body: any, options?: HttpRequestOptions): Observable<...>
第二个参数应该是请求体,第三个才是配置选项。你错误地将配置选项当作了请求体,导致observe: 'response'并未被应用,所以订阅时只能拿到响应体字符串。
修正后的代码
1. 修复postComment方法
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, observe: 'response' as const // 明确类型避免TS报错 }; // 正确传递:URL → 请求体 → 配置选项 return this.httpClient.post<string>( `${environment.apiBase}/social/comments/postcomment/`, comment, // 将comment作为请求体传递 httpOptions ); }
注意:如果后端期望请求体是一个包含
comment字段的JSON对象(而非纯字符串),请将请求体改为{ comment: comment }。
2. 订阅时读取状态码
修正后,订阅中的value将是完整的HttpResponse对象,此时可以正常读取状态码、响应头和响应体:
this.socialService.postComment(this.contentCode, comment, this.answeredComment.id).subscribe( value => { console.log(value); // 输出完整的HttpResponse对象 console.log(value.status); // 输出201 console.log(value.headers); // 输出响应头对象 console.log(value.body); // 输出"OK" } );
内容的提问来源于stack exchange,提问作者BraveOtter
相关产品推荐
相关产品推荐

