Angular 2 - handle every http response

739 views Asked by At

How can I create something like callback for every http response to check if server return 401 error to redirect user on login page.

1

There are 1 answers

0
baidario On BEST ANSWER

I found what i need

import {XHRBackend, Request, XHRConnection, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

export class CustomXHRBackend extends XHRBackend {
  public createConnection(request: Request): XHRConnection {
    let connection: XHRConnection = super.createConnection(request);
    connection.response = connection.response
      .catch(this.handleError);

    return connection;
  }

  private handleError(error: Response | any) {
    console.log(error['status']);
    if(error['status'] === 401) {
      console.log('Navigate to login page.');
    }

    // <- HERE I CAN CATCH EVERY NEEDED ERROR USING switch operator

    return Observable.throw(error);
  }
}