Angular4拦截http错误

时间:2017-10-14 18:43:34

标签: angular http interceptor

我写了一个Angular4 http拦截器。它适用于请求和非错误响应。但是,例如,我无法拦截401,拦截器甚至没有被触发。有人知道如何拦截401,例如转发到登录页面吗?

这是我的代码:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { PersistenceService, StorageType, IPersistenceContainer } from 'angular-persistence';
import { Router } from '@angular/router';

@Injectable()

export class TokenInterceptor implements HttpInterceptor {

    storageContainer: IPersistenceContainer

    constructor (
        public persistenceService: PersistenceService,
        public router: Router
    ) {
        this.storageContainer = persistenceService.createContainer(
      'org.ptnc.auth', 
      {type: StorageType.SESSION, oneUse: false}
    )
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer ' + this.storageContainer.get('jwt')
            }
        })

        return next.handle(req)
        .do(event => {
            if(event instanceof HttpResponse ){
                console.log('intercepts the response', event)
                // this.router.navigate(['/auth/login'])
            }
            if(event instanceof HttpErrorResponse){
                console.log('the real error')
            }
        })
    }

}

3 个答案:

答案 0 :(得分:1)

如果HttpClient为响应引发错误,则会在可观察链中冒泡。

您必须在catch observable上使用next.handle(req)来捕获并处理来自HttpClient的错误:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // ...
    return next.handle(req)
      .do(event => {
         // ...
      })
      .catch(error => {
        // handle the error;

        // rethrow it
        return Observable.throw(error);
      });
}

答案 1 :(得分:1)

这是我的http.service.ts

的一部分示例
  get(request: string): Observable<any> {
    return this._http.get(`${this.actionUrl}${request}`)
      .map(res => this.extractData(res))
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    return res.json();
  }

  private handleError(error: Response) {
    console.log('Error', error);
    return Observable.throw(error.json().error || 'Server error');
  }

希望它也有帮助

答案 2 :(得分:1)

要使用HttpErrorResponse截取HttpInterceptor,您必须使用rxjs运算符以do方式进行拦截。

import 'rxjs/add/operator/do';

return next.handle(req).do(event => {
    console.log('handle success event');
    return event;
}, error_event => {
    console.log('handle error event, ie 404 or 500');
    return error_event;
});

注意: catch没有为我做这个技巧,因为http错误没有触发throw()错误