将默认Firebase配置注入Angular App

问题描述:

我需要使用Firebase托管中的默认配置来配置应用程序,因为我正在将其部署到多个项目中.

I have the need to use the default configuration from the firebase hosting for an app because I am deploying it to multiple projects.

如果这是普通的html应用,则可以使用:

If this was a normal html app you would use:

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/6.1.0/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#reserved-urls -->

<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>

但是我使用的是有角度的应用程序,因此我想将其注入应用程序模块的初始化中.我试图做这样的事情:

But I am using an angular app so I want to inject it in the initialize of the app module. I tried to do something like this:

let firebaseConfig = environment.firebase;

if (environment.production) {
  console.log('loading init');
  fetch('/__/firebase/init.json').then(async response => {
    firebaseConfig = await response.json();
  });
}

@NgModule({
  declarations: [
    AppComponent
  ],

  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(firebaseConfig),

那只是我的应用程序模块的一部分,但是您可以了解一下.如果它正在生产中,我想从 init.json 中提取它,但如果不是,我想从环境设置中提取它.

That is just part of my app module but you can kind of get the idea. If it is in production, I want to pull it from the init.json but if not I want to pull it from the environment setting.

由于这是一个异步操作,我如何使其工作?

And since this is an async operation, how can I make it work?

以下是您可以尝试的选项:

Here's an option you can try:

app.module.ts

@NgModule({
  ...
  imports: [
    BrowserModule,
    AngularFireModule,
  ]
  ...

main.ts

import { FirebaseOptionsToken } from '@angular/fire';

if (environment.production) {
  enableProdMode();
}

function loadConfig() {
  return environment.production ?
    fetch('/__/firebase/init.json')
      .then(response => response.json())
    : Promise.resolve(environment.firebase);
}

(async () => {
  const config = await loadConfig();

  platformBrowserDynamic([{ provide: FirebaseOptionsToken, useValue: config }])
     .bootstrapModule(AppModule)
     .catch(err => console.error(err));
})();