相关疑难解决方法(0)

如何在Angular 2中处理200以外的http状态代码

现在,我做http请求的方式(借用这个答案)是这样的:

POST(url, data) {
        var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
        headers.append("Content-Type", 'application/json');

        if (authtoken) {
        headers.append("Authorization", 'Token ' + authtoken)
        }
        headers.append("Accept", 'application/json');

        var requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this.apiURL + url,
            headers: headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(requestoptions))
        .map((res: Response) => {
            if (res) {
                return { status: res.status, json: res.json() }
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,除非如果返回的状态代码不是200,angular2将失败.例如,如果用户想要发布某些东西而服务器返回400,则角度2将抛出异常:

未捕获的异常:[object Object]

我怎么能避免这个?我想在我的应用中处理这些状态代码,以增强用户体验(显示错误等)

typescript angular

37
推荐指数
1
解决办法
9万
查看次数

标签 统计

angular ×1

typescript ×1