Initializing another module inside my module's forRoot method

410 views Asked by At

I'm creating a library module (AuthModule), which depends on a third party module (AngularFire's AngularFireModule). My library (AuthModule) will be used inside a few other applications.

Thing is, to be able to import AngularFire I have to pass it some configurations, like this:

@NgModule({
    declarations: [ ... ],
    imports: [
        AngularFireModule.initializeApp(enviroment.firebaseOptions)
    ],
    providers: [...],
    exports: []
})
export class AuthModule { }

The problem is that I don't want to hardcode the options/configurations within my library, because these will vary depending on which application is using it.

I was thinking on using a forRoot method in my module in a way that it receives the config as a paramater and then uses it to initialize the third-party module (AngularFireModule).

But is it possible to import another module inside a forRoot method? How?

Thanks!

1

There are 1 answers

0
jparg On

You could use Angular's forRoot method and initialize the AngularFireModule there instead (this is for older versions of the Firebase SDK, as used in the question, newer versions have a different syntax).

AuthModule:

...
@NgModule({
  // do not initialize AngularFireModule here
  imports: [AngularFireModule, ...],
  declarations: [...],
  exports: [AngularFireModule, ...],
  providers: [...]
})
export class AuthModule {
   static forRoot(firebaseOptions: any): ModuleWithProviders<AuthModule> {

   [...]
   // initialize AngularFireModule here
   AngularFireModule.initializeApp(firebaseOptions)

  return {
    ngModule: AuthModule,
    providers: [...]
  };
 }

 static forFeature(): Type<AuthModule> {
   return AuthModule;
 }

}

AppModule:

@NgModule({
declarations: [ ... ],
imports: [
    // your module here with the firebase info
    AuthModule.forRoot(enviroment.firebaseOptions)
],
providers: [...],
exports: []
})

export class AppModule { }