我需要服务返回保留状态等的承诺,并将响应数据作为成功和错误回调的对象。
有建议的方法吗?这就是我目前所做的(并且有效):
return this.http.get(url)
.map(res => this.commonService.extractData(res))
.toPromise()
.catch(res => this.commonService.handleError(res));
CommonService:
extractData(res: Response): Response {
res.data = res.text() ? res.json() : null;
return res;
}
handleError(res: Response): Response {
res.data = res.text() ? res.json() : null;
return Promise.reject(res);
}
答案 0 :(得分:1)
对于observable,我在utils.ts文件中封装了extract / handle错误函数。功能定义如下:
/**
* Extracts the information received as response from a HTTP request
* @param res a HTTP response
*/
export const extractData = (res: Response) => {
const body = res.json();
return body || {};
};
/**
* Handles a possible error in the response of an HTTP request
* @param error a HTTP response with error status code
*/
export const handleError = (error: Response | any): Observable<string> => {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.message || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} Details: ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return _throw(errMsg);
};
当我导出它们时,我可以直接将它们用作map / catch中的方法参数。 例如:
getPlant(id: string): Observable<IPlantDetail> {
return this._http.get(`${this._endPoint}/${id}`)
.map(extractData)
.catch(handleError)
.delay(300);
}
很可能你也可以为承诺做同样的事。
希望有所帮助