什么是httpinterceptor相当于angular2

什么是httpinterceptor相当于angular2

本文介绍了什么是httpinterceptor相当于angular2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angularjs,我们有HTTP拦截

In angularjs, we have http interceptor

$httpProvider.interceptors.push('myHttpInterceptor');

,使我们可以挂接到所有的HTTP调用,以及显示或隐藏加载条,做记录等。

with which we can hook into all http calls, and show or hide loading bars, do logging, etc..

什么是angular2等价?

What is the equivalent in angular2?

推荐答案

作为@君特指出了这一点,就没有办法注册拦截器。您需要延长 HTTP 类,并把你的拦截处理各地HTTP调用

As @Günter pointed it out, there is no way to register interceptors. You need to extend the Http class and put your interception processing around HTTP calls

首先,你可以创建一个扩展一个类 HTTP

First you could create a class that extends the Http:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

如下所述

和注册它:

and register it as described below:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

要求 requestError 种可调用对象的方法前加入。

The request and requestError kinds could be added before calling the target methods.

对于响应之一,你需要塞些异步处理到现有的加工链。这取决于你的需要,但你可以使用运营商(如 flatMap )的观测。

For the response one, you need to plug some asynchronous processing into the existing processing chain. This depends on your need but you can use operators (like flatMap) of Observable.

最后的 responseError 一个,你需要调用运营目标的呼叫。您将会收到通知这种方式时,在响应中出现错误。

Finally for the responseError one, you need to call the catch operator on the target call. This way you will be notified when an error occurs in the response.

这个链接可以帮助你:




  • Handling refresh tokens using rxjs
  • Angular 2 - How to get Observable.throw globally

这篇关于什么是httpinterceptor相当于angular2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:03