Angular 9-打字稿-headers.set-不添加标题 [英] Angular 9 - typescript - headers.set - not adding header
本文介绍了Angular 9-打字稿-headers.set-不添加标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用有角的注入器添加不记名令牌
尽管代码已执行,但未添加标头
那里有很多不同的代码,我尝试了其中的一些,它们都导致相同的问题
there are many different codes out there, I tried some of them, they all lead to the same issue
没有发送承载与请求
在下图中,我在 clone/headers.set 处停了下来,但是即使经过这一步,标题映射仍然为空
in the below image I stopped at clone/headers.set, but even after that step, the headers map is still empty
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private appService: AppService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
let authentication: Authentication = this.appService.getUserSession();
const isLoggedIn = authentication && authentication.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
//------------------------------------- add id's
let body = request.body;
if(!body)
{
body={};
}
body['clientId'] = environment.clientId;
body['clientSecret'] = environment.clientSecret;
request = request.clone({
body: body
});
//--------------------------------------- add jwt
if(authentication)
{
request = request.clone(
{
headers: request.headers.set('Bearer', authentication.token)
}
);
}
return next.handle(request);
}
}
感谢您帮助我完成这一任务
thanks for helping me on this one
推荐答案
根据clone()方法原型,您获得了一个对象属性来设置标头(名为setHeaders)
According to the clone() method prototype, you got an object property to set headers (named setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
您应该执行以下操作
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);
这篇关于Angular 9-打字稿-headers.set-不添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文