Search code examples
angularfirebaseionic-frameworkionic4

Where do I initialize Firebase JS SDK inside Ionic4 + Angular project?


I have a simple question: Where do I initialize the firebase SDK's inside Ionic4 + Angular project?

is it inside the app.module.ts file? Or in the app.component.ts file? I tried to initialize it inside the app.module.ts but without success (using code below):

import { NgModule } from '@angular/core';
import { RouteReuseStrategy } from '@angular/router';
import { IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';

import { environment } from 'src/environments/environment';
import firebase from 'firebase/compat/app'; //I get an error here

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    firebase.initializeApp(environment.firebase)
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}

But I get an error saying (line with the firebase.initializeApp(environment.firebase)):

Type 'App' is not assignable to type 'any[] | Type<any> | ModuleWithProviders<{}>'.
Type 'App' is missing the following properties from type 'Type<any>': apply, call, bind, prototype, and 4 more.

Solution

  • To use Firebase with an Angular project you'll have to use angular/fire which is the officially supported package for Angular and Firebase development.

    The most basic configuration can be found in their quickstart guide here and will look something like this in your app module

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { AngularFireModule } from '@angular/fire/compat';
    import { environment } from '../environments/environment';
    
    @NgModule({
      imports: [
        BrowserModule,
        AngularFireModule.initializeApp(environment.firebase)
      ],
      declarations: [ AppComponent ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule {}