如何在角度中捕获http服务中的错误条件

时间:2017-12-26 12:34:38

标签: angular angular-services angular-http

manageHttp(method: any, url: any, body: any) {
    this.headers = this.config.setHeaders();
    var urlto = this.config.serverUrl + '' + url;
    if (method === 'get') {
        this.toRunMethod = this.http.get(urlto, { headers: this.headers });
    } else if (method === 'post') {
        this.toRunMethod = this.http.post(this.config.serverUrl + url, body, { headers: this.headers });
    } else if (method === 'put') {
        this.toRunMethod = this.http.put(this.config.serverUrl + url, body, { headers: this.headers });
    } else if (method === 'delete') {
        this.toRunMethod = this.http.delete(this.config.serverUrl + url, { headers: this.headers });
    }
    return this.toRunMethod.map((response: Response) => {
        // More than one user - logout
        if (response && response.json().error_code == 0) {
            return response.json();
        }
    }, (error) => {
        this.authGuardMethod(error);
    });
}

我网络中的响应就像这样

{error: "token_expired"}

但不幸的是,我的authGuardMethod()方法没有抓住它,我的意思是它没有进入这种状态

}, (error) => {
        this.authGuardMethod(error);
    });

它甚至没有进入authGaurd方法,任何我的代码,

 authGuardMethod(error: any) {
    if (error) {
        if (error.statusText === "Unauthorized") {
            let url =  this.router.url.split("/");
            if(url.length > 1){
                if(url[1] != 'estimate-assembly-cost' && url[1] != 'placeorder' ){
                    this.router.navigate(['/']);
                }
            }
            localStorage.setItem("error", '1');
        } else if(error.statusText === "Bad Request") {
            this.router.navigate(['']);
            localStorage.removeItem('adminUser');
            localStorage.removeItem('token');
        }
    } else {
        localStorage.setItem("error", '2');
        this.router.navigate(['/']);
    }
}

我一直在努力找到这个,但没有运气。

1 个答案:

答案 0 :(得分:-1)

从我的观点来看,在请求期间处理错误的最佳方法是创建一个拦截器并在全局级别处理错误请求。

https://angular.io/guide/http#intercepting-all-requests-or-responses

希望它会有所帮助。