我在后端SpringBoot中创建了httpInterceptor,并将我的API密钥保存在application.properties中。
我必须在Http头中的某个角度服务中启用HttpInterceptor,但我不知道如何才能做到这一点
发布于 2021-10-21 05:27:31
你是说怎么注册你的拦截器?您可以将其作为提供程序添加到模块中:
@NgModule({
imports: [
HttpClientModule
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: BackendRequestInterceptor, multi: true},发布于 2021-10-21 15:07:32
是!注册拦截器,就像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://stackoverflow.com/questions/69656112
复制相似问题