【问题标题】:Angular - HTTP Interceptor And Configuration loaded on APP_INITIALIZEAngular - 在 APP_INITIALIZE 上加载的 HTTP 拦截器和配置
【发布时间】:2019-04-03 15:31:51
【问题描述】:

我有一个带有工厂的配置模块,该工厂在应用程序初始化时执行 (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 完成?

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


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

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

【问题讨论】:

    标签: angular configuration angular-http-interceptors angular-lifecycle-hooks


    【解决方案1】:

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

    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 不会唤醒拦截器)

    导出类 AuthenticationService 实现 AuthService { API_URL = this.configService.tokenServer; ....

    在您的情况下,您似乎也缺少依赖项。缺少一些代码,但在 AuthenticationService 模块中您可能应该声明依赖关系,例如:

    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, deps: [AuthenticationService ], multi: true },
    

    并且变量初始化应该依赖于Service构造函数:

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

    应该是:

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

    希望即使真的迟到了也能有所帮助

    【讨论】:

    • 谢谢!我会尽快尝试。
    • 谢谢,这真的很有帮助。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2017-11-07
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2018-07-08
    • 2020-11-08
    相关资源
    最近更新 更多