如何为每个http响应创建回调,以检查服务器是否返回401错误以在登录页面上重定向用户。
答案 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);
}
}