在Angular 2中检测服务器连接错误(404状态)

时间:2017-08-27 13:54:33

标签: angular

我想检测服务器的连接错误,以便我可以向用户显示相应的消息。

当后端服务器(Web API)关闭,并且我尝试使用http.get访问此服务器上的方法时,我希望获得具有404状态或某种状态的响应连接错误。相反,我正在

  

“状态响应:URL为0:null”

目前尚不清楚。 那么我怎样才能检测到连接错误呢?

这是相关代码:

登录组件:

this.loginService.tryLogin(userName, password).subscribe(_loginStatus => {
  //Some operations
 },
 _err => this.errMsg = _err; // this.errMsg will be displayed to the user
);

登录服务

tryLogin(user: string, pwd: string): Observable<LoginStatus> {
 return this.http.get(this.serverUri + `Login/?username=${user}&password=${pwd}`)
   .map(response => response.json())
   .catch(err => this.handleError(err));
}

private handleError(error: any) {
  const err = (error.json() ? error.json() : error);
  console.log(err);
  return Observable.throw(err);
}

1 个答案:

答案 0 :(得分:1)

您可以在此处使用Http Interceptors。在Angular中使用新的HttpClientModule拦截器很容易。

import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){ // here you can even check for err.status == 404 | 401 etc
            console.log("Error Caught By Interceptor");
            //Observable.throw(err); // send data to service which will inform the component of the error and in turn the user
        }
    });
  }
}

在Appmodule中注册,如

providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass: 
              AngularInterceptor, multi: true } ]
    ],

有关Http客户端和拦截器的更多信息,请查看此link