0

I need in my angular 2 app a HTTP interceptor, which checks the HTTP status code of each response. If the status code is 401, I want to redirect the user to the login site.

Is there a simple way to implement this?

Thanks!!

Martin Schagerl
  • 583
  • 1
  • 7
  • 19

1 Answers1

1

You could implement a class that extends the Http one:

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

If 401 errors occur as this level, you could intercept them globally in the catch callback. You can leverage injected elements to handle them. For example, the Router.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Whith this approach I get always the following error: catch is not a function I demonstrate this already: https://github.com/lexon0011/IssueDemonstrator Could someone reproduce the error? – Martin Schagerl Apr 23 '16 at 15:29
  • See this question: http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function-in/34515276#34515276 You need to import the catch operator like for the map one (replace map by catch in the answer ;-)) – Thierry Templier Apr 23 '16 at 15:56