代码之家  ›  专栏  ›  技术社区  ›  Sergio Daniel Coronel Malvarez

Angular-HTTP拦截器和配置加载到APP\u INITIALIZE上

  •  2
  • Sergio Daniel Coronel Malvarez  · 技术社区  · 6 年前

    我有一个配置模块,它的工厂在应用程序初始化时执行(APP\u 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;
    ....
    

    有没有办法把拦截器初始化推迟到APP\u初始化完成?

    我的目标是为所有环境创建一个独特的构建。


    我找不到一个好的、可维护的、整洁的解决方案。

    1 回复  |  直到 5 年前
        1
  •  6
  •   RiccardoBucchi    6 年前

    有没有办法把拦截器的初始化推迟到 应用程序初始化程序已完成?

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

    我个人使用了deg answer,在APP\u INITIALIZE中只使用HttpBackend依赖项而不是HttpClient,因为我曾经通过http调用检索配置。Http调用产生了拦截器,拦截器基本上需要配置,最终形成循环依赖关系(HttpBackend不会唤醒拦截器)

    导出类AuthenticationService实现AuthService{ API\ URL=this.configService.tokenServer。。。。

    { 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;
        }
    

    希望它能帮上忙,即使真的很晚了