gpt4 book ai didi

Angular - 在 APP_INITIALIZE 上加载的 HTTP 拦截器和配置

转载 作者:行者123 更新时间:2023-12-03 09:28:48 26 4
gpt4 key购买 nike

我有一个带有工厂的配置模块,它在应用程序初始化时执行(APP_INITIALIZER)

export function ConfigFactory(config: ConfigService) {
const res = () => config.load();
return res;
}
...
{
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}

如果我在页面/组件上打印数据,一切正常。

问题是当我尝试在从 HttpInterceptor 调用的服务中使用配置时:
    {
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},

拦截器:
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any> , next: HttpHandler): Observable<HttpEvent<any>> {

this.authenticationService.getAccessToken().subscribe((token: string) => { this.accessToken = token.toString(); });
this.authenticationService.getCurrentUser().subscribe((currentU: string) => { this.currentUser = currentU.toString(); });
if (this.accessToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.accessToken}`,
actor: this.currentUser,
// modulo: 'AltaActivoFijo'
}
});
}
return next.handle(request);
}

身份验证服务:
export class AuthenticationService implements AuthService {
API_URL = this.configService.tokenServer;
....

问题是 configService 是未定义的。

有没有办法将拦截器初始化推迟到 APP_INITIALIZER 完成?

我的目标是为所有环境提供独特的构建。

在尝试了不同的选择之后:

对于这个问题,我找不到一个好的、可维护的和简洁的解决方案。

最佳答案

Is there any way to postpone an interceptors initilization until APP_INITIALIZER is finished?



How to make an angular module to ignore http interceptor added in a core module

我个人使用 deg 答案,其中在 APP_INITIALIZE 中简单地使用 HttpBackend 依赖而不是 HttpClient,因为我曾经通过 http 调用检索配置。 Http Call 兴起了 Interceptor,基本上需要 Configuration,最终形成循环依赖。 (HttpBackend 不会唤醒拦截器)

export class AuthenticationService implements AuthService { API_URL = this.configService.tokenServer; ....



在您的情况下,您似乎也缺少依赖关系。缺少一些代码,但在 AuthenticationService 模块中您可能应该声明依赖项,例如:
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, deps: [AuthenticationService ], multi: true },

和变量初始化应该依赖于服务构造函数:
export class AuthenticationService implements AuthService {
API_URL = this.configService.tokenServer;
....

应该:
export class AuthenticationService implements AuthService {
constructor(configService: ConfigService) {
this.API_URL = configService.tokenServer;
}

希望它有帮助,即使真的迟到了

关于Angular - 在 APP_INITIALIZE 上加载的 HTTP 拦截器和配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com