简体   繁体   English

截取角度响应头

[英]Intercept response headers in angular

I am creating an token based authentication system in angular5. 我正在angular5中创建基于令牌的身份验证系统。 With every request I will send a header containing the token ( X-SDB-AUTH-TOKEN ) and with some response with 401 or 403 status code I sed a response header to identify the type of foribidden status like forbidden because key not match return response header AUTH-STATUS :1 and if user not active status AUTH-STATUS:2 etc.. I want to check in the interceptor and if the status code is 401 or 403 and if AUTH-STATUS:2 redirect to user not active page otherwise if the status code is 401 or 403 and if AUTH-STATUS:1 redirect to key not match page . 对于每个请求,我将发送一个包含令牌的标头( 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 How can I verify response code and header value together. 如何一起验证响应代码和标头值。 How can we easily read response headers and error code. 我们如何轻松读取响应标头和错误代码。 My code till now is 到目前为止,我的代码是

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

The catch operator has two parameters .catch((error, caught) => {}) . catch运算符具有两个参数.catch((error, caught) => {})

error is of type HttpErrorResponse , it has a field headers which allows you to get access to the headers collection. error的类型为HttpErrorResponse ,它具有一个字段headers ,使您可以访问标题集合。

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

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