简体   繁体   English

Angular4拦截器变化响应

[英]Angular4 Interceptor change response

I have an auth HttpInterceptor : 我有一个auth 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();
      }
    });
  }
}

This interceptor works fine, but when i'm getting 401 i'm redirecting user to login page, but the error still goes to the service, and in that service i'm showing error msg, and this msg showing at signin page. 这个拦截器工作正常,但是当我得到401我将用户重定向到登录页面时,但错误仍然发送到服务,并且在该服务中我显示错误消息,并且这个消息显示在登录页面。 So i want to change response or do something in if (err instanceof HttpErrorResponse && err.status === 401) { block, to not returning error in this case. 所以我想改变响应或做一些if (err instanceof HttpErrorResponse && err.status === 401) { block,在这种情况下不返回错误。

return Observable.empty();

is not working 不管用

next.handle(clone).do() - this is what's causing such behavior. next.handle(clone).do() - 这就是造成这种行为的原因。 do() operator is intended only to provide side-effects, but it does not actually affect data flow and error handling in the observable pipe. do()运算符仅用于提供副作用,但它实际上不会影响可观察管道中的数据流和错误处理。 Essentially it is saying "when this happens please do this and that and then continue as if there's no do() section at all". 基本上它是说“当发生这种情况时,请执行此操作,然后继续,好像根本没有do()部分”。 If you want to suppress errors then you need to use catch() operator. 如果要抑制错误,则需要使用catch()运算符。

Code would be almost the same: 代码几乎相同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM