What is the equivalent of httpinterceptor in angular2?

In angularjs we have an http interceptor

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

with the help of which we can connect to all http-calls, as well as show or hide loading columns, keep a log, etc.

What is equivalent in angular2?

+45
angular
Feb 19 '16 at 6:09
source share
10 answers

As @ Günter noted, there is no way to register interceptors. You need to extend the Http class and move the handling of interception around HTTP calls

First you can create a class that extends 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 can be added before calling the target methods.

For response one, you need to hook some asynchronous processing into an existing processing chain. It depends on your needs, but you can use Observable operators (like flatMap ).

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

These links can help you:

  • Handling update tokens with rxjs
  • Angular 2 - How to Get Observable.throw Globally
+59
Feb 19 '16 at 7:48
source

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 (generic): the new HttpClient API HttpClient is an evolution of the existing Angular HTTP API that comes with it in a separate package, @ angular / generic / http. This structure ensures that codebases can slowly migrate to the new API.

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

  • Typed, synchronous access to the response body, including support for JSON body types.
  • JSON is assumed default and no longer needs explicit analysis
  • Interceptors let you insert middleware logic into the pipeline
  • Immutable request / response objects
  • Events for loading and downloading requests and responses
  • Validation structure after validation and flash testing

original

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

see also

+11
Feb 19 '16 at 6:49
source

This repository implements an implementation for the Http @ angular / core-like service: https://github.com/voliva/angular2-interceptors

You simply declare the provider of this service in bootstrap, adding any interceptors that you need and will be available for all 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] }) 
+10
Sep 28 '16 at 13:50
source

DEPRICATED SINCE Angular 4.3 (HttpInterCeptors are back in 4.3)

You can create your own HTTP class and use the rxjs Subject Service to reuse your custom Http class and implement your actions in a custom class.

Implement your custom Http class using the "HttpSubjectService", which contains some rxjs objects.

 import { Injectable } from '@angular/core'; import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { HttpSubjectService } from './httpSubject.service'; @Injectable() export class CustomHttp extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private httpSubjectService: HttpSubjectService) { super(backend, defaultOptions); //Prevent Ajax Request Caching for Internet Explorer defaultOptions.headers.append("Cache-control", "no-cache"); defaultOptions.headers.append("Cache-control", "no-store"); defaultOptions.headers.append("Pragma", "no-cache"); defaultOptions.headers.append("Expires", "0"); } request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { //request Start; this.httpSubjectService.addSpinner(); return super.request(url, options).map(res => { //Successful Response; this.httpSubjectService.addNotification(res.json()); return res; }) .catch((err) => { //Error Response. this.httpSubjectService.removeSpinner(); this.httpSubjectService.removeOverlay(); if (err.status === 400 || err.status === 422) { this.httpSubjectService.addHttp403(err); return Observable.throw(err); } else if (err.status === 500) { this.httpSubjectService.addHttp500(err); return Observable.throw(err); } else { return Observable.empty(); } }) .finally(() => { //After the request; this.httpSubjectService.removeSpinner(); }); } } 

Custom module for registering your CustomHttp class - here you overwrite the default Http implementation from Angular using your own CustomHttp implementation.

 import { NgModule, ValueProvider } from '@angular/core'; import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http'; //Custom Http import { HttpSubjectService } from './httpSubject.service'; import { CustomHttp } from './customHttp'; @NgModule({ imports: [ ], providers: [ HttpSubjectService, { provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, httpSubjectService: HttpSubjectService) => { return new CustomHttp(backend, defaultOptions, httpSubjectService); }, deps: [XHRBackend, RequestOptions, HttpSubjectService] } ] }) export class CustomHttpCoreModule { constructor() { } } 

now we need an implementation of HttpSubjectService where we can SubScribe for our rxjs users when they are called with the following statement.

 import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class HttpSubjectService { //https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md //In our app.component.ts class we will subscribe to this Subjects public notificationSubject = new Subject(); public http403Subject = new Subject(); public http500Subject = new Subject(); public overlaySubject = new Subject(); public spinnerSubject = new Subject(); constructor() { } //some Example methods we call in our CustomHttp Class public addNotification(resultJson: any): void { this.notificationSubject.next(resultJson); } public addHttp403(result: any): void { this.http403Subject.next(result); } public addHttp500(result: any): void { this.http500Subject.next(result); } public removeOverlay(): void { this.overlaySubject.next(0); } public addSpinner(): void { this.spinnerSubject.next(1); } public removeSpinner(): void { this.spinnerSubject.next(-1); } } 

in order to invoke your custom Realizations, we need to Connect to Subjects, for example. "app.component.ts".

 import { Component } from '@angular/core'; import { HttpSubjectService } from "../HttpInterception/httpSubject.service"; import { Homeservice } from "../HttpServices/home.service"; @Component({ selector: 'app', templateUrl: './app.component.html', }) export class AppComponent { private locals: AppLocalsModel = new AppLocalsModel(); constructor(private httpSubjectService : HttpSubjectService, private homeService : Homeservice) {} ngOnInit(): void { this.notifications(); this.httpRedirects(); this.spinner(); this.overlay(); } public loadServiceData(): void { this.homeService.getCurrentUsername() .subscribe(result => { this.locals.username = result; }); } private overlay(): void { this.httpSubjectService.overlaySubject.subscribe({ next: () => { console.log("Call Overlay Service"); } }); } private spinner(): void { this.httpSubjectService.spinnerSubject.subscribe({ next: (value: number) => { console.log("Call Spinner Service"); } }); } private notifications(): void { this.httpSubjectService.notificationSubject.subscribe({ next: (json: any) => { console.log("Call Notification Service"); } }); } private httpRedirects(): void { this.httpSubjectService.http500Subject.subscribe({ next: (error: any) => { console.log("Navigate to Error Page"); } }); this.httpSubjectService.http403Subject.subscribe({ next: (error: any) => { console.log("Navigate to Not Authorized Page"); } }); } } class AppLocalsModel { public username : string = "noch nicht abgefragt"; } 

SINCE Angular 4.3 you can use InterCeptors

In Angular 4.3, you have built-in Interceptors where you can implement your own things, such as redirecting for a 500 server error

 import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class SxpHttp500Interceptor implements HttpInterceptor { constructor(public router: Router) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).do(evt => { }).catch(err => { if (err["status"]) { if (err.status === 500) { this.router.navigate(['/serverError', { fehler: JSON.stringify(err) }]); } } return Observable.throw(err); }); } } 

you need to register this in your main module in an array of suppliers

 import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { Router } from '@angular/router'; import { SxpHttp500Interceptor } from "./sxpHttp500.interceptor"; .... providers: [ { provide: HTTP_INTERCEPTORS, useFactory: (router: Router) => { return new SxpHttp500Interceptor(router) }, multi: true, deps: [Router] } ] 
+7
Jan 21 '17 at 21:31 on
source

With the release of Angular 4.3.1, there is now an interface called HttpInterceptor .

Here's a link to the docs: https://angular.io/api/common/http/HttpInterceptor

Here is an example implementation.




This will be an implementation of the interceptor class.

It is basically written like any other service:

 @Injectable() export class ExceptionsInterceptor implements HttpInterceptor { constructor( private logger: Logger, private exceptionsService: ExceptionsService, private notificationsService: NotificationsService ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request) .do((event) => { // Do nothing here, manage only errors }, (err: HttpErrorResponse) => { if (!this.exceptionsService.excludeCodes.includes(err.status)) { if (!(err.status === 400 && err.error['_validations'])) { this.logger.error(err); if (!this.notificationsService.hasNotificationData(err.status)) { this.notificationsService.addNotification({ text: err.message, type: MessageColorType.error, data: err.status, uid: UniqueIdUtility.generateId() }); } } } }); } } 

Then, since you will see this as a regular service, you should add this line to your application module providers:

 { provide: HTTP_INTERCEPTORS, useClass: ExceptionsInterceptor, multi: true } 

Hope this helps.

+4
Jul 25 '17 at 8:08
source

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

+1
Jul 19 '17 at 7:30
source

I released an interceptor with the following node module. We created this module for our internal purpose, finally we released the npm package manager npm install angular2 -resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

0
Nov 09 '16 at 6:17
source

As @squadwuschel noted, work is underway to provide this functionality with @ angular / http. This will be in the form of the new HttpClient API.

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

0
Jul 03 '17 at 21:54
source

Try Covalent from Teradata , they provide many extensions for Angular and Angular Material.

Mark the HTTP part, it contains the missing HTTP interceptor in Angular and RESTService (similar to restatular).

I authenticated the JWT token through Covalent HTTP in my example. Please check here.

https://github.com/hantsy/angular2-material-sample/blob/master/src/app/core/auth-http-interceptor.ts

Read my development notes, Check Token Based Tokens through IHttpInterceptor .

0
Jul 14 '17 at 11:07
source

Angular2 donot httpinterceptor support as angular

Here is a great example of using httpinterceptor in angular2.

https://github.com/NgSculptor/ng2HttpInterceptor

0
Aug 23 '17 at 6:11
source



All Articles