在使用 HttpClient
的 Angular 服务中,我创建了一个方法,该方法从 POST
返回原始 HTTP 响应。 :
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
//observe: 'response'
}),
observe: 'response' as 'body'
};
forgotLogin(requestData: PUMRequestData): Observable<HttpResponse<string>> {
return this.http.post<HttpResponse<string>>("http://...", requestData, this.httpOptions);
然后在我的组件中,我只查看原始 http 响应中的状态和正文。
this.api.forgotLogin(pumRequestData).subscribe(response => {
this.hStatus = response.status;
this.hBody = response.body;
});
问题是如果响应状态不在
200
系列,然后 HttpClient
引发错误。在我的用例中,我只想获取请求状态和正文,而不管状态是什么,我想根据组件中的状态决定要采取的操作,而不是在服务中的错误处理程序中。我一直试图找出一些棘手的方法来在服务中创建一个错误处理程序,该处理程序只返回(可观察的)HTTP
响应,并且无法-甚至不确定这是否是正确的方法。那么当状态不是 200 系列时,如何将原始 http 响应返回给我的组件?
最佳答案
这对我有用 HttpClient not able to retrieve plain text .
That's right.
It works when there is no generic code applied to it.
it will work for:
http.get(url, {responseType: 'text'}
关于Angular HttpClient : How to get raw HTTP response, 即使出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209997/