2017-06-13 133 views
0

我需要该服务来返回一个承诺保持状态等等,并且将响应数据作为成功和错误回调的对象。从Angular http服务中提取数据

有没有建议的方法?这是我目前做的(和作品):

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); 
    } 

回答

1

对于观测,我封装提取物/处理utils.ts文件里的错误功能。功能定义如下:

/** 
* 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); 
}; 

当我导出它们,我可以直接使用它们作为在地图/捕获方法参数。 例如:

getPlant(id: string): Observable<IPlantDetail> { 
    return this._http.get(`${this._endPoint}/${id}`) 
     .map(extractData) 
     .catch(handleError) 
     .delay(300); 
    } 

最有可能你可以做同样的承诺。

希望它有帮助

+0

谢谢你的回答。这与我已经做的非常接近。因此,使用第一个map()和catch()将数据属性添加到响应的想法是可以接受的,对吧? – Olezt

+0

或多或少,只要从htt.get(...)返回的内部观察值不会引发错误,map就会被执行 –