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!!
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!!
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.