Angular4拦截器变化响应

时间:2017-09-20 19:05:18

标签: angular angular-http-interceptors angular4-httpclient

我有一个身份验证HttpInterceptor

import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, 
HttpRequest} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService,
              private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authHeader = this.authService.getToken();
    const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
    return next.handle(clone).do(() => {
}, err => {
  console.log(err);
  if (err instanceof HttpErrorResponse && err.status === 401) {
    this.authService.clearToken();
    this.router.navigate(['/auth/signin']);
    return Observable.empty();
      }
    });
  }
}

这个拦截器工作正常,但是当我获得401时,我将用户重定向到登录页面,但错误仍然发送到服务,并且在该服务中我显示错误消息,这个消息显示在登录页面。所以我想更改响应或在if (err instanceof HttpErrorResponse && err.status === 401) {块中执行某些操作,以便在这种情况下不返回错误。

return Observable.empty();

无效

1 个答案:

答案 0 :(得分:8)

next.handle(clone).do() - 这就是造成这种行为的原因。 do()运算符仅用于提供副作用,但它实际上不会影响可观察管道中的数据流和错误处理。基本上它是说“当发生这种情况时,请执行此操作,然后继续,好像根本没有do()部分”。如果要抑制错误,则需要使用catch()运算符。

代码几乎相同:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService,
                private router: Router) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authHeader = this.authService.getToken();
        const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
        return next.handle(clone).catch(err => { // <-- here
            console.log(err);
            if (err instanceof HttpErrorResponse && err.status === 401) {
                this.authService.clearToken();
                this.router.navigate(['/auth/signin']);
                return Observable.empty();
            }
            // we must tell Rx what to do in this case too
            return Observable.throw(err);
        });
    }
}