Angular 9 - typescript - headers.set - ไม่เพิ่มส่วนหัว
Oct 02 2020
ฉันพยายามใช้หัวฉีดเชิงมุมเพื่อเพิ่มโทเค็นผู้ถือ
แม้ว่าโค้ดจะถูกเรียกใช้งาน แต่ก็ไม่ได้เพิ่มส่วนหัว
มีรหัสที่แตกต่างกันมากมายฉันลองใช้บางรหัสทั้งหมดนี้นำไปสู่ปัญหาเดียวกัน
ไม่มีผู้ถือคนใดส่งคำขอ
ในภาพด้านล่างฉันหยุดที่clone / headers.setแต่แม้หลังจากขั้นตอนนั้นแผนที่ส่วนหัวยังคงว่างเปล่า
@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);
}
}
ขอบคุณที่ช่วยฉันเรื่องนี้
คำตอบ
1 Adjunta Oct 02 2020 at 10:01
ตามต้นแบบวิธีการ clone () คุณมีคุณสมบัติของวัตถุเพื่อตั้งค่าส่วนหัว (ชื่อ setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
คุณควรทำดังต่อไปนี้
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);