嗨,我正在尝试通过http拦截器添加自定义标头,以下是我的代码
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { StorageService } from 'src/app/services/storage-service';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class AuthorizationHeaderInterceptor implements HttpInterceptor {
constructor(private storageService:StorageService ){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let authToken = this.storageService.getAuthorizationToken();
const authReq = req.clone({
headers: req.headers.set('Authorization', authToken)
});
return next.handle(authReq);
}
}
使用上述代码,我得到“ TypeError:无法读取未定义的属性” length”。但是,随着以下更改,错误消失了,但没有设置授权标头。
const authReq = req.clone();
authReq.headers.set('authorization',authToken);
代码中可能是什么问题。
谢谢。
答案 0 :(得分:0)
我个人使用setHeaders而不是标题
//here you add the bearer in every request
addAuthentication(req: HttpRequest<any>): HttpRequest<any> {
const headers: any = {};
const authToken = this.userStore.getToken(); // get the token from a service
if (authToken) {
headers['authorization'] = authToken; // add it to the header
req = req.clone({
setHeaders: headers
});
}
return req;
}