6

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?

1 Answer 1

8

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)); })(); 
Sign up to request clarification or add additional context in comments.

3 Comments

In case you are like me and thought that <script src="/__/firebase/6.1.0/firebase-app.js"></script> and <script src="/__/firebase/init.js"></script> were also necessary for this to work... they aren't. '/__/firebase/init.json' seems to be available immediately with no further scripts required.
At December 1st of 2021 the FirebaseOptionsToken didn't work with my current version of AngularFire, maybe because another code uses compat modules, so FirebaseOptionsToken should change to FIREBASE_OPTIONS from "@angular/fire/compat", and add another provider for AngularFireModule (from same module). Then you import and provide AngularFireModule in AppModule. github.com/angular/angularfire/issues/…
How can we do the auth module and the firestore module ? ERROR Error: Uncaught (in promise): Error: Component auth has not been registered yet Error: Component auth has not been registered yet

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.