以角度截取响应头

问题描述 投票:0回答:1

我正在angular5中创建一个基于令牌的身份验证系统。对于每个请求,我将发送一个包含令牌(X-SDB-AUTH-TOKEN)的标头,并使用401或403状态代码的一些响应,我发送一个响应头来标识禁止状态的类型,如禁止,因为键不匹配返回响应头AUTH-STATUS :1,如果用户没有活跃状态AUTH-STATUS:2等。我想检查拦截器,如果状态代码是401 or 403,如果AUTH-STATUS:2重定向到user not active page否则,如果状态代码是401 or 403,如果AUTH-STATUS:1重定向到key not match page。如何一起验证响应代码和标头值。我们如何轻松读取响应头和错误代码。我的代码到现在为止

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from 
'@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';

 @Injectable()
    export class TokenInterceptor implements HttpInterceptor {

  constructor(private router: Router) {
 }

intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {

if (localStorage.getItem('authToken')) {    
  req = req.clone({
    setHeaders: {
      'X-SDB-AUTH-TOKEN': localStorage.getItem('authToken')
    }
  });

}
return next.handle(req)
  .catch((error, caught) => {
    if (error.status === 401 || error.status === 403) {
       localStorage.removeItem('authToken');  
       this.router.navigate(['/testLogin']);   
    }

    return Observable.throw(error);
  }) as any;
 }  
}
angular interceptor response-headers
1个回答
0
投票

catch运算符有两个参数.catch((error, caught) => {})

error的类型为HttpErrorResponse,它有一个字段headers,允许您访问header集合。

© www.soinside.com 2019 - 2024. All rights reserved.