0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. This is very close to what I already do. So the idea to use first map() and then catch() to add the data property to response is acceptable, right?
More or less, map will be executed, as long as the internal observable returned from htt.get(...) does not throw an error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.