Search code examples
angularfirebaseionic-frameworkfirebase-realtime-databaseangular-module

Configure Firebase environment dynamically in Angular


I have a list of data in my mobile app and for each data I can have different firebase configuration file. Requirement is, When I click on any data, it will make a request to our server and pull the firebase configuration from there.

Once the configuration is available to Mobile app, it will use this configuration to connect with firebase and then retrieve data and perform some action. Requirement

Is it possible to achieve this?

Or more specifically, Can I do AngularFireModule.initializeApp(environment) in my constructor or in ngOnInit()in mycomponent.component.ts rather than doing it in myModuleName.Module.ts .


Solution

  • This is how I get it done. Rather than using it in app module, I specifically used it for the module which needed it.

    In module.ts

        import { AngularFirestoreModule } from 'angularfire2/firestore';
        import { AngularFireDatabaseModule } from 'angularfire2/database';
        @NgModule({
          declarations: [
           ...
          ],
          imports: [
            ...
            AngularFirestoreModule,
            AngularFireDatabaseModule],
          exports: [
           ...      ],
          providers: [
           ...
          ]
        })
    

    In the component.ts

    import { AngularFirestore } from 'angularfire2/firestore';
    import { _firebaseAppFactory } from "angularfire2/firebase.app.module";
    
    
      angFirestore: AngularFirestore
    
    ngOnInit(){
        this.angFirestore = new AngularFirestore(_firebaseAppFactory(environment.firebase, environment.localAppName.toString()), false);
        }
    
    ionViewWillUnload(){
          this.clearFirebaseInfo();
          if(this.angFirestore && this.angFirestore.app){
            this.angFirestore.app.delete();
          }
       }