angularangular-module

how to use a parameter in a app.module function


I have a module to import which needs a variable for forRoot, for this, I need the application to be started and use a service to get:

export function getAuthConfig(configService: ConfigService):OauthConfig[] {    
      return configService.getOauthConfig();
}


function initializeAppFactory(httpClient: HttpClient, configService: ConfigService): () => Observable<any> {
  return () => httpClient.get(url)
  .pipe(
   tap((res) => {
    configService.loadAppConfig(<AppConfig>res);
   })
);
}

@NgModule({
providers: [
  ConfigService,
  {
    provide: APP_INITIALIZER,
    useFactory: initializeAppFactory,
    deps: [HttpClient, ConfigService],
    multi: true
  }
],
imports: [   
  OauthModule.forRoot(
  {
    configurations: getAuthConfig() //include configservice here
  })
],
bootstrap: [AppComponent],
declarations: [
 AppComponent
 ]
})
export class AppModule {
}

Solution

  • You can define the method in configService as static.

    export class getOauthConfig {
        static getOauthConfig() {
            ....
        }
    }
    

    Then in the module you can call it statically.

    export function getAuthConfig():OauthConfig[] {    
          return ConfigService.getOauthConfig();
    }
    
    
    function initializeAppFactory(httpClient: HttpClient, configService: ConfigService): () => Observable<any> {
      return () => httpClient.get(url)
      .pipe(
       tap((res) => {
        configService.loadAppConfig(<AppConfig>res);
       })
    );
    }
    
    @NgModule({
    providers: [
      ConfigService,
      {
        provide: APP_INITIALIZER,
        useFactory: initializeAppFactory,
        deps: [HttpClient, ConfigService],
        multi: true
      }
    ],
    imports: [   
      OauthModule.forRoot(
      {
        configurations: getAuthConfig() //include configservice here
      })
    ],
    bootstrap: [AppComponent],
    declarations: [
     AppComponent
     ]
    })
    export class AppModule {
    }