我在后端 SpringBoot 中創建了 httpInterceptor,并將我的 API 密鑰保存在 application.properties 中。
我必須在 Http 標頭中的 Angular 服務中的某處啟用 HttpInterceptor,但我不知道該怎么做
uj5u.com熱心網友回復:
你的意思是如何注冊你的攔截器?您可以將其添加為模塊中的提供者:
@NgModule({
imports: [
HttpClientModule
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: BackendRequestInterceptor, multi: true},
uj5u.com熱心網友回復:
是的!像 Andreas 在他的回答中發布的那樣注冊攔截器,然后實作它。這是我的一個專案中的一個示例:
import { Injectable } from "@angular/core";
import { HttpInterceptor } from '@angular/common/http';
import { AuthDirectusService } from './auth-directus.service';
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
constructor(private authService: AuthDirectusService) {}
intercept(req, next) {
if(this.authService.getToken() != null)
{
let tokenizedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken()}`
}
})
return next.handle(tokenizedReq);
}else{
let tokenizedReq = req.clone({
setHeaders: {
}
})
return next.handle(tokenizedReq);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331725.html
標籤:爪哇 有角的 弹簧靴 angular-http-拦截器
下一篇:限制sqlite中列的值
