加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 http结果的正确错误处理

发布时间:2020-12-17 06:48:22 所属栏目:安全 来源:网络整理
导读:参见英文答案 Angular2 handling http response????????????????????????????????????3个 我一直在使用angular.io文档中使用的http错误处理策略: getHeroes () { return this.http.get(this._heroesUrl) .map(res = Hero[] res.json().data) .catch(this.ha
参见英文答案 > Angular2 handling http response????????????????????????????????????3个
我一直在使用angular.io文档中使用的http错误处理策略:

getHeroes () {
    return this.http.get(this._heroesUrl)
                    .map(res => <Hero[]> res.json().data)
                    .catch(this.handleError);
    }
    private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

在某些情况下,我将收到204状态代码(无数据),而不是JSON响应.在这种情况下,在通过res.json()解析结果失败之前不会调用错误处理程序,因此传递给handleError的错误是“error.json不是函数”.

如何查询响应流以检查200(OK)状态代码或响应头内容类型“application / json”,并通过更相关的错误消息发出错误处理程序的信号?

解决方法

http .get('Some Url') .map(res => { 
// If request fails,throw an Error that will be caught 
if(res.statu != 200) { 
throw new Error('This request has failed ' + res.status); } // If everything went fine,return the response 
else {return res.json(); 
} })

这可能对你有所帮助.

这只是为了了解如何使用响应中的状态,您可以根据您的要求进行修改.

仅对非200代码抛出错误检查此commit

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读