【问题标题】:Detecting server connection error (404 status) in Angular 2在 Angular 2 中检测服务器连接错误(404 状态)
【发布时间】:2017-08-28 14:16:03
【问题描述】:

我想检测到服务器的连接错误,以便向用户显示适当的消息。

当后端服务器(Web API)关闭时,我尝试使用 http.get 访问此服务器上的方法,我希望得到一个 404 状态的响应,或者某种连接错误。相反,我得到了

“响应状态:0 对于 URL: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);
}

【问题讨论】:

  • 你检查过这个吗? ${pwd} 后缺少结束单引号
  • @PadmanabanGokula 哎呀,现在修复它

标签: angular


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2017-06-25
    • 1970-01-01
    • 2023-03-31
    • 2021-11-29
    • 2015-12-29
    相关资源
    最近更新 更多