当我使用HttpInterceptor添加标头时,它们被添加到lazyUpdate中,而不是标头数组中

时间:2019-09-03 02:22:11

标签: angular http-headers angular-http-interceptors

我已经通过Angular中的HttpInterceptor添加了授权标头,但是输出似乎不正确。根据添加了标头后的JSON输出,这感觉太笨拙以至于无法正确添加标头,或者我访问它们的方式有误吗?:

headers["lazyUpdate"].forEach(x=>{x.name=='Authorization'}).value

目标是返回Bearer mystring

拦截器称为:

  

{“ url”:“ https://myurl”,“ body:{},” reportProgress“:false,   “ withCredentials”:false,   “ responseType”:“ json”,   “ method”:“ POST”,   “ headers”:{“ normalizedNames”:{},“ lazyUpdate”:null,“ headers”:{}},“ params”:{“ updates”:null,“ cloneFrom”:null,“ encoder”:{}, “ map”:null},“ urlWithParams”:“ myurl”}

token.interceptor.ts:13拦截器添加了令牌:

  

{“ url”:“ myurl”,   “身体”:{},   “ reportProgress”:否,   “ withCredentials”:false,   “ responseType”:“ json”,   “ method”:“ POST”,   “ headers”:{“ normalizedNames”:{},“ lazyUpdate”:[ {“ name”:“ Authorization”,“ value”:“ Bearer mystring”,“ op”:“ s”} ],   “ headers”:{},“ lazyInit”:{“ normalizedNames”:{},“ lazyUpdate”:null,“ headers”:{}}},“ params”:{“ updates”:null,“ cloneFrom”:null ,“ encoder”:{},“ map”:{}},“ urlWithParams”:“ myurl”}

我的TokenInterceptor类:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {   
    console.log('interceptor called: '+JSON.stringify(request))

    let r = request.clone({
      headers: request.headers.set('Authorization', `Bearer ${localStorage.getItem("id_token")}`)
    });
    console.log('interceptor added token: '+JSON.stringify(r))
    return next.handle(r);
  }
}

0 个答案:

没有答案