Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Default Firebase Config into Angular App

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

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),

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?

like image 841
Jonathan Avatar asked Jun 03 '19 16:06

Jonathan


1 Answers

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));
})();
like image 84
yurzui Avatar answered Nov 10 '22 22:11

yurzui