Angular 2 - 处理每个http响应

时间:2016-12-14 22:12:48

标签: angular typescript xmlhttprequest angular2-http

如何为每个http响应创建回调,以检查服务器是否返回401错误以在登录页面上重定向用户。

1 个答案:

答案 0 :(得分:3)

我找到了我需要的东西

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