What is httpinterceptor equivalent in angular2?

2019-01-03 13:56发布

In angularjs, we have http interceptor

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

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

What is the equivalent in angular2?

标签: http angular
10条回答
劳资没心,怎么记你
2楼-- · 2019-01-03 13:57

Angular 4.3 now supports Http interceptor out-of-the-box. Check it out how to use them: https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors

查看更多
孤傲高冷的网名
3楼-- · 2019-01-03 13:58

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

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]
  })
]);

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

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.

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.

This links could help you:

查看更多
成全新的幸福
4楼-- · 2019-01-03 13:59

I have released interceptor with following node module. We was create this module for our internal purpose finally we released in npm package manager npm install angular2-resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-03 14:01

update

The new HttpClient module introduced in Angular 4.3.0 supports interceptors https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0

feat(common): new HttpClient API HttpClient is an evolution of the existing Angular HTTP API, which exists alongside of it in a separate package, @angular/common/http. This structure ensures that existing codebases can slowly migrate to the new API.

The new API improves significantly on the ergonomics and features of the legacy API. A partial list of new features includes:

  • Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download
  • Post-request verification & flush based testing framework

original

Angular2 doesn't have (yet) interceptors. You can instead extend Http, XHRBackend, BaseRequestOptions or any of the other involved classes (at least in TypeScript and Dart (don't know about plain JS).

See also

查看更多
仙女界的扛把子
6楼-- · 2019-01-03 14:02

There's an implementation for a Http @angular/core-like service in this repository: https://github.com/voliva/angular2-interceptors

You just declare the provider for that service on bootstrap, adding any interceptors you need, and it will be available for all the components.

import { provideInterceptorService } from 'ng2-interceptors';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    MyHttpInterceptor,
    provideInterceptorService([
      MyHttpInterceptor,
      /* Add other interceptors here, like "new ServerURLInterceptor()" or
         just "ServerURLInterceptor" if it has a provider */
    ])
  ],
  bootstrap: [AppComponent]
})
查看更多
Ridiculous、
7楼-- · 2019-01-03 14:04

As @squadwuschel pointed out, work is underway to get this functionality into @angular/http. This will be in the form of a new HttpClient API.

See https://github.com/angular/angular/pull/17143 for more details and current status.

查看更多
登录 后发表回答