How to use angular 2 service which returns http promise

若如初见. 提交于 2019-12-05 10:04:23

You need to return response.json() from promise then callback:

load(): Promise<any> {
    return this.http.get(this.BASEURL + 'api/client/hotel/load')
        .toPromise()
        .then(response => {
            return response.json();
        })
        .catch(err => err);
}

The dfsq's answer is correct, but for the completeness' sake, below is an example according to the official Angular.io recommendations:

load(): Promise<any> {
    return this.http.get(this.BASEURL + 'api/client/hotel/load')
        .toPromise()
        .then(response: Response) => response.json() || {})
        .catch((error: Response | any) =>
        {
            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();

            return Promise.reject(errMsg);
        });
}

Key differences:

  • handle empty response in the then;
  • pretty up the error before throwing it further.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!