【问题标题】:How can I intercept http errors with angular2?如何使用 angular2 拦截 http 错误?
【发布时间】:2015-12-30 00:26:23
【问题描述】:

是否有类似于 angular 1.x 的Interceptor API 的 API?

我希望能够在应用程序启动时添加拦截器

  • 每当返回401 状态码时显示登录对话框
  • 每当返回 5xx 状态代码时显示一般错误消息

对于应用程序发出的每个 http 请求。

【问题讨论】:

    标签: angularjs http angular http-response-codes


    【解决方案1】:

    您可以创建自己的 HTTPConnection 来处理错误并在引导时将其注入到根应用程序组件中。

    export class CustomHTTPConnection implements Connection
    {
    }
    

    然后在引导时注入它,如下所示

    bootstrap([provider(Connection,{useClass:CustomHTTPConnection}]);
    

    如果您不想提供自定义连接类,您可以为每个单独的请求执行此操作,因为 Http 返回一个 observable,它作为 3 个参数:onNext、onError、onCompleted。

    您可以按如下方式使用它:

    class Component
    {
    constructor(private httpService:HttpService){
    }
    onInit(){
     this.httpService.getData().subscribe(
      ()=>{},  //on Next
      ()=>{}   //onError
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 1970-01-01
      • 2018-07-08
      • 2020-03-24
      • 2016-09-20
      • 1970-01-01
      • 2023-03-19
      • 2017-02-09
      • 2014-05-26
      相关资源
      最近更新 更多