如何获取发布 api 调用的响应,然后在页面上显示错误


const tokenClean = sessionStorage.getItem('token')?.replace(/[:{}"]/g, '');
const tokenFinal = tokenClean?.replace(/token/g, '');
const headers = {
'Authorization': `Bearer ${tokenFinal}`,
'Body': '{}',

};
this.http.post(apiUrl + "token/vendor/request/getproductlist", headers, { headers })
.subscribe((data: any) =>
{ this.listDropDown2 = data; }

这是我调用 api post 请求的代码,我如何获得错误然后在页面上显示它?如果有的话

由于Angular的HttpClient使用了RxJs可观察的处理程序,因此监视任何HTTP调用中的错误与监视任何其他可观察对象中的错误相同,例如,通过提供第二个回调函数作为subscribe()(docs)的参数。

注意:答案通过提供一个"观察者"对象作为参数来证明这一点subscribe()其中包含成功(next)和错误(error)处理程序作为该对象的键

这将返回一个HttpErrorResponse类 (docs),其中包含有关错误的所有元数据:

postProductList() {
const tokenClean = sessionStorage.getItem('token')?.replace(/[:{}"]/g, '');
const tokenFinal = tokenClean?.replace(/token/g, '');
const headers = {
'Authorization': `Bearer ${tokenFinal}`,
'Body': '{}',
};
this.http.post(
apiUrl + "token/vendor/request/getproductlist",
headers,
{ headers }
)
.subscribe({
next: (data: any) => {
// any API success handling logic goes here (e.g. for http codes 2xx and 3xx)
this.listDropDown2 = data;
},
error: (httpError: HttpErrorResponse) => {
// any API error handling logic goes here (e.g. for http codes 4xx and 5xx)
const errorValue: any | null = httpError.error;
const errorCode: number = httpError.status;
console.error(`Endpoint returned error ${errorValue} with status code ${errorCode}`)
}
})
}

相关内容

最新更新