Search code examples
javascriptangularfirebaseangularfire2

How to initialize firebase dynamically in angular 7 after getting the configuration via http call


i'm trying to initialize the firebase dynamically after getting the config file via http call using @angular/fire. but all the documents and search is pointing me to initialize it in app.module.ts like below.

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        BrowserModule,
        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule,
        IonicModule.forRoot(),
        AppRoutingModule,
    ],
    providers: [
        StatusBar,
        SplashScreen,
        {provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
} 

is it possible to call the initializeApp in any service like below

@Injectable({
    providedIn: 'root'
})
export class FirebaseSyncService {

    constructor(private httpClient: HttpClient) {}

    initializeFirebase() {
        const url = 'http://localhost:3000/get-config?db=12345';
        this.httpClient.get<any>(url).subscribe(response => {
            AngularFireModule.initializeApp(response.config);
        });
    }
}


Solution

  • Found a simple hack after many hair pulling.

    my environment.ts file

    export const environment = {
        production: false,
        firebase: getConfig()
    };
    
    function getConfig() {
        let config;
        let request = new XMLHttpRequest();
        try {
            request.open('GET', 'http://localhost:3000/index/get-config', false);  // `false` makes the request synchronous
            request.send(null);
    
            if (request.status === 200) {
                console.log(request.responseText);
                config = request.responseText;
            }
    
            return JSON.parse(config);
        } catch (e) {
            console.error('environment:getConfig: unable to get api key : ', e);
        }
    
        return config;
    }
    
    

    My Lazy loaded module import:

    @NgModule({
        entryComponents: [],
        imports: [
            BrowserModule,
            AngularFireModule.initializeApp(environment.firebase),
            AngularFirestoreModule,
            IonicModule.forRoot(),
            AppRoutingModule,
        ],
    })
    
    

    Next in service or any component, inject and use as normal

     constructor(private afs: AngularFirestore) {}
    
    

    Hope this helps for anyone in the future.