Firebase initializing late in app.component.ts


#1

My Ionic 3 app uses Firebase, which is initialized in app.component.ts, and also Geofire (which relies on Firebase), which is initialized in a provider. I noticed that sometimes when I launch the app, the Geofire provider runs first (before app.component), causing an error because Firebase isn’t initialized yet. I even wrapped the GeoFire initialization in

platform.ready().then()

…, and wrapped the firebase initialization in platform.ready().then() in app.component, but it still runs before the initialization in app.component.

I thought everything in app.component always runs first before any providers and such, when the app is launched. How can I force the provider to run only after Firebase is fully initialized in app.component.ts? Or is there a way to detect from the provider whether Firebase has been initialized?

Thanks.


#2

See: https://angular.io/guide/styleguide#core-feature-module

core.module.ts:

...

import { ENV } from '@env';

@NgModule({
  imports: [
    AngularFireModule.initializeApp(ENV.firebase),
    AngularFirestoreModule,
    AngularFireAuthModule,
    AngularFireStorageModule,
    CommonModule,
    HttpClientModule,
    IonicModule,
    LocalStorageModule,
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: ENV.production }),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [ HttpClient ]
      }
    })
  ],
  exports: [],
  declarations: [],
  providers: [
    AuthService,
    ENV.production ? { provide: ErrorHandler, useClass: BrewErrorHandler } :
      { provide: ErrorHandler, useClass: IonicErrorHandler},
    GeolocationService,
    ...
    { provide: LoggerService, useClass: ConsoleLoggerService },
    MapsApiLoaderService,
    ServiceWorkerService,
    ...
  ]
})
export class CoreModule {
  constructor( @Optional() @SkipSelf() parentModule: CoreModule,
               private translate: TranslateService,
               private afs: AngularFirestore) {

    throwIfAlreadyLoaded(parentModule, 'CoreModule');

    translate.setDefaultLang('en');

    // https://github.com/angular/angularfire2/issues/1575
    const settings = { timestampsInSnapshots: true };
    afs.app.firestore().settings(settings);
  }
}

app.module.ts:

@NgModule({
  declarations: [ AppComponent ],
  imports: [
    BrowserModule,
    CoreModule,
    IonicModule.forRoot(AppComponent, {
      backButtonText: ''
    })
  ],
  bootstrap: [ IonicApp ],
  entryComponents: [ AppComponent ],
  providers: []
})
export class AppModule {}