Rob
Rob

Reputation: 73

AngularFirestore was already initialized on the [DEFAULT] Firebase App with different settings

So I have this small issue.

I have an Angular app and in the app.module.ts I initialize AngularFire

imports: 
[...
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFireFunctionsModule,
...]

Now I have multiple smaller modules, like for example LazyModule. This module is loaded in app-routing.module.ts like so:

{
    path: 'lazyModule',
    loadChildren: () => import('./modules/lazyModule/lazyModule.module').then(m => m.LazyModule)
},

Inside this LazyModule I do not import AngularFire again and I have a LazyComponent which requires the AngularFirestore

export class LazyComponent {
  constructor(private firestore: AngularFirestore){}
}

For some reason, each time I navigate to this component, AngularFire tries to reinitialize and throws this error:

AngularFirestore was already initialized on the [DEFAULT] Firebase App with different settings.

Why does this happen?

Upvotes: 1

Views: 424

Answers (1)

Joseph Zabinski
Joseph Zabinski

Reputation: 850

Whenever you import AngularFire, it apparently caches an object containing the current submodule's configuration in globalThis.ɵAngularfireInstanceCache. If you import the same submodule again, it checks the current instance's configuration against the cached configuration. (The same submodule might be imported if multiple Angular child modules rely on AngularFire.) If the configurations don't match, then this error appears: [AngularFire submodule] was already initialized on the [DEFAULT] Firebase App with different settings. See this code.

I know that the original question says that AngularFire was loaded in app.module, and the LazyModule did not import AngularFire. A tip about that:

Look for Angular services that depend on AngularFire. Depending on where they are providedIn, they might be loaded in modules that otherwise don't involve AngularFire, and that are missing configuration defined elsewhere. This is very easy to miss.

For example, I was configuring Auth's USE_EMULATOR in a child module, and using Auth with no configuration in an Angular guard in the main module. The child module loaded with no errors, but the error was appearing for me upon navigation whenever the guard was involved. When the guard's dependencies were imported, a new instance of AngularFire Auth would be initialized, but was created with a different configuration than the one first cached for the child module.

I fixed it by injecting all AngularFire configuration in the main module. Child modules apparently inherit things injected at the main module level.

Upvotes: 1

Related Questions