请问如何解析API返回给我的error body。
这是我的代码:
login(username,password){
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post(this.configEnvironment.url() + "oauth/access_token",
JSON.stringify(
{
username: username,
password: password,
grant_type: "password",
client_id: "xxxxxxx",
client_secret: "xxxxxxxx"
}
),
{ headers }
)
.map(res => res.json())
.catch((err:any) =>{
console.log(err);
return Observable.throw(new Error(err));
});
}
我可以使用这个访问 URL、状态、statusText 等:
err.status,err,url,error.statusText
我的问题是我无法获取错误正文的值。
最佳答案
您的catch
实际上收到了一个Response
。您可以使用 json()
import { Response } from "@angular/http";
...
.catch((err:Response) =>{
let details = err.json().error;
console.log(details);
return Observable.throw(new Error(details));
});
注意:这个答案是关于 @angular/http
库的。从 Angular 5 开始,这个库已被弃用,取而代之的是 @angular/common/http
关于angularjs - 解析 Angular 2 中的错误主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067617/