我正在使用Angular 2 HTTP,並且有一個訂閱響應的組件。但是,當出現錯誤時,catch方法不會將錯誤返回給訂閱的組件。它只是把它扔進控制檯。Angular 2錯誤處理 - 發送到訂閱組件
saveFinalize(fcData: LastForecastInterface) {
let responseData = JSON.stringify(fcData);
let body = responseData;
const headers = new Headers();
headers.append('Content-Type', 'application/json;charset=UTF-8');
return this.http.post('/saveFinalize', body, { headers: headers })
.map((data: Response) => data.json())
.catch(this.handleError);
}
public handleError(error: Response | any) {
console.log('err: ', error)
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
// return Observable.throw(errMsg);
return errMsg;
}
而且我已經訂閱的組件不回來的響應
saveFinalize() {
this.loadingData = true;
return this.httpService.saveFinalize(this.getFc.fcData)
.subscribe(response => {
this.loadingData = false;
console.log(response);
let saveResponse = response.success ? 'Successfully Saved Finalized!' : 'Error Saving Finalized! - ' + response.message;
let respType = response.success ? 'success' : 'danger';
this.alertSvc.showAlert(saveResponse, respType);
});
}
'handleError'函數需要返回'catch'的'Observable'才能工作。看到這個鏈接:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/catch.md – eminlala