![](/img/trans.png)
[英]How to handle if API response is a string instead of JSON in Ionic + Angular
[英]Angular / Ionic - Handle JSON “error” property
我正在使用TypeScript,Angular 5.0。 這個界面總結了我的后端響應:
export interface JSONResponse {
error?: {
code: number,
message: string
};
data?: {};
}
我的服務中從服務器獲取數據的功能是:
httpGet(url: string, httpParams: HttpParams) {
return new Promise((resolve, reject) => {
this.http.get<LoginResponse>(url, {params: httpParams})
.subscribe(res => {
resolve(res.data);
}, err => {
// handle http get related errors here
console.log(err);
});
});
}
然后使用該服務的組件來呈現模板:
buttonClicked(event) {
this.myService.httpGet('myAPIurl', someRequestParams)
.then((data) => {
this.myData = data;
}, (err) => {
console.log(err);
});
}
在哪里可以處理來自后端的響應的錯誤檢查?
也就是說,如果存在屬性data
,則響應成功並且可以正確處理我的數據; 如果存在屬性error
,我將代碼/消息錯誤通知用戶。
如果您需要以更通用的方式進行操作,則可以使用IonicErrorHandler 。
IonicErrorHandler會攔截默認的控制台錯誤處理,並在使用Ionic的Dev Build Server時將運行時錯誤顯示為覆蓋圖。
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicErrorHandler } from 'ionic-angular';
@NgModule({
providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler }]
})
class AppModule {}
如果要自定義它,也可以這樣做。
class MyErrorHandler implements ErrorHandler {
handleError(err: any): void {
// do something with the error
}
}
@NgModule({
providers: [{ provide: ErrorHandler, useClass: MyErrorHandler }]
})
class AppModule {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.