You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 19中Configuration工厂函数无法获取已加载的config.json配置(出现undefined)的问题求助

Angular 19中Configuration工厂函数无法获取已加载的config.json配置(出现undefined)的问题求助

我现在在做GitOps场景下的Angular应用,需要为每个环境替换config.json,而且想尽量简化实现(比如不用NgRx这类状态管理库)。目前遇到了一个头疼的问题:

我用provideAppInitializer来加载config.json,之后想在Configuration的工厂函数里用加载好的配置,设置OpenAPI生成代码的basePath,但每次拿到的配置都是undefined。

先贴一下我的相关代码:

应用初始化与配置提供者代码

provideAppInitializer(() => inject(ConfigService).getConfig$()),
{ 
  provide: Configuration, 
  deps: [ConfigService], 
  useFactory: (configService: ConfigService) => 
    makeEnvironmentProviders([{ 
      provide: Configuration, 
      useValue: new Configuration({ 
        basePath: configService.get().maintenanceApi.basePath 
      }) 
    }]) 
},

ConfigService核心代码

getConfig$(): Promise<void> {
  return lastValueFrom(
    this.http.get<Config>('/assets/config.json').pipe(
      tap(c => {
        this.config = c;
        console.log("loaded config", c)
      }),
      take(1)
    )
  ).then(() => {});
}

get(): Config {
  return this.config;
}

奇怪的是,运行代码时我明明看到console.log("loaded config", c)的输出在undefined错误之前,但工厂函数里调用configService.get()就是拿不到值。有没有大佬能帮我分析下问题出在哪?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 07:12:58