【问题标题】:Angular AppConfig loaded from server, but needed in module setup从服务器加载的 Angular AppConfig,但在模块设置中需要
【发布时间】:2019-09-03 19:30:28
【问题描述】:

网上有很多关于在 Angular 中获取配置的示例(现在是 8 个)APP_INITIALIZER,这里有一个总结:https://davembush.github.io/where-to-store-angular-configurations/

NgModule 终于长成这样了

@NgModule({
 // ...
  imports: [
    BrowserModule,
    HttpClientModule,
    // My modules here
    AngularFireModule.initializeApp(firebaseConfigHere)
  ],
  providers: [{
      provide: APP_INITIALIZER,
      useFactory: load,
      deps: [
        HttpClient,
        ConfigService
      ],
      multi: true
    }
  ],
 // ...
})

我被卡住了,因为我有一些配置初始化的模块,其中一个是臭名昭著的 AngularFireModule 像这样

AngularFireModule.initializeApp(firebaseConfigHere)

我尝试了很多技巧,但似乎无法掌握它,我们如何将从服务器加载的配置传递到导入中设置的模块?

注意导入在 APP_INITIALIZER 之前触发

【问题讨论】:

    标签: angular ng-modules angular-providers


    【解决方案1】:

    1:提供fire模块,不调用initializeApp; 2:为FirebaseOptionsToken令牌提供工厂ConfigService依赖 3:提供任何你会传递给 initializeApp 作为FirebaseNameOrConfigToken 的第二个参数

    @NgModule({
      imports: [BrowserModule,HttpClientModule,AngularFireModule],
      providers: [
       {/* your APP_INITIALIZER here */}
       { provide: FirebaseNameOrConfigToken, useValue: null},
       { 
        provide: FirebaseOptionsToken,
        useFactory: (configService: ConfigService) => configService.pathToFirebaseConfig},
        deps: [ConfigService]
      ]
    })
    

    这将使工厂被懒惰地调用。请注意,您不能将与 firebase 模块相关的任何内容注入到 ConfigService 或其他初始化程序依赖项中,因为我建议的工厂将在配置到达之前被调用。

    【讨论】:

    • 我试过了,APP_INITIALIZER 仍然比工厂运行的要晚于令牌,并且它已经是设置配置的承诺,所以当它加载配置时,工厂已经尝试过检索pathToFirebaseConfig。你有没有实现过这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多