Search code examples
angulartypescriptangularfire2angular-library

Pass environment.ts To Angular Library Module for use in imports


I have an angular monorepo and I'd like reuse the following module per project but using that project's environment. Ideally without copying and pasting this multiple times into each project.

import { environment } from '../environments/environment';

@NgModule({
  imports: [
    provideFirebaseApp(() => initializeApp(environment.firebaseConfig))
  ]
})
export class AngularFirebaseV7Module { }

This uses the angular firebase version 7 new API detailed here

In order to do this I'm trying to pull this into a library.

Based on Pass environment.ts To Angular Library Module I see I can provide the environment as a config and pass in via

AngularFirebaseV7Module.forRoot(environment.firebaseConfig)
import { InjectionToken, ModuleWithProviders, NgModule } from '@angular/core';

import { initializeApp, provideFirebaseApp } from '@angular/fire/app';

// what I want to get rid of:
import { environment } from '../environments/environment';

interface IFirebaseConfig {
    apiKey: string
    authDomain: string
    projectId: string
    storageBucket: string
    messagingSenderId: string
    appId: string
    measurementId: string
}

export const FIREBASE_CONFIG = new InjectionToken<IFirebaseConfig>('FIREBASE_CONFIG');

@NgModule({
  declarations: [],
  imports: [
    provideFirebaseApp(() => {
      // I don't want to use `environment.firebaseConfig` but config
      return initializeApp(environment.firebaseConfig)
    })
  ]
})
export class AngularFirebaseV7Module {

  static forRoot(config: IFirebaseConfig): ModuleWithProviders<AngularFirebaseV7Module> {

    // have access to config here but not for imports
    console.log(config)

    return {
      ngModule: AngularFirebaseV7Module,
      providers: [
        {
          provide:  FIREBASE_CONFIG,
          useValue: config
        }
      ]
    };
  }

}

but how do I use this config within the imports provideFirebaseApp(() => initializeApp(config))?


Solution

  • provideFirebaseApp function takes callback as an argument and that callback receive Injector as a parameter.

    export function provideFirebaseApp(fn: (injector: Injector) => IFirebaseApp, ...deps: any[]): ModuleWithProviders<FirebaseAppModule> {
      return {
        ...
      };
    }
    

    https://github.com/angular/angularfire/blob/8d5bc1205b88a3d4cd0ffb16e9614ed7ae4a014c/src/app/app.module.ts#L71

    So you can use that injector to retrieve your config:

    provideFirebaseApp((injector) => {
      return initializeApp(injector.get(FIREBASE_CONFIG))
    }),