Angular 6 HTTP拦截器未设置标头

时间:2018-08-28 07:05:26

标签: angular typescript angular-http-interceptors

我正在尝试制作jsonwebtoken拦截器,由于某种原因,它根本没有设置标头。

对于我的提供者来说

import { TokenInterceptorService } from './token-interceptor.service';
...
providers: [AuthService, AuthGuard, {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptorService,
        multi: true
}]

我的TokenInterceptorService也很简单:

import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {

    constructor() { }

    intercept(req, next) {

        let tokenizedReq = req.clone({
            setHeader: {
                Authorization: 'Bearer xx.yy.zz'
            }
        })

        return next.handle(tokenizedReq);
    }
}

如果我登录tokenizedReq,则标题不包含任何内容。我一定在俯视什么。

2 个答案:

答案 0 :(得分:1)

setHeader一无是处。

使用setHeaders: {}之类的

        let tokenizedReq = req.clone({
            setHeaders: {
                Authorization: 'Bearer xx.yy.zz'
            }
        })

或使用

    let tokenizedReq = req.clone({
        headers: req.headers.set('Authorization','Bearer xx.yy.zz'),
    })    

答案 1 :(得分:0)

在Observable的帮助下尝试。

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
    request = request.clone({
      setHeaders: {
        Authorization: 'Bearer xx.yy.zz'
      }
    });
    return next.handle(request);
  }