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 發布請求的代碼,我如何得到錯誤然后在頁面上顯示?如果有一個
uj5u.com熱心網友回復:
由于 AngularHttpClient使用了 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}`)
}
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/515400.html
