Olezt
Olezt

Reputation: 1738

Extract data from Angular http service

I need the service to return a promise keeping status etc. plus having the response data as object both for success and error callbacks.

Is there a suggested way? This is what I currently do (and works):

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

Upvotes: 0

Views: 609

Answers (1)

Jota.Toledo
Jota.Toledo

Reputation: 28434

For observables, I capsulated the extract/handle error functions inside of a utils.ts file. The functions are defined as follows:

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

When I export them, I can use them directly as method parameters in map/catch. For example:

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

Most likely you could do the same for promises.

Hope it helps

Upvotes: 1

Related Questions