Access injectable value to SubModule when importin

2020-04-20 04:23发布

问题:

Okay, so, here's some context...

I've got a feature module that requires a string value to be passed to its forRoot static method when imported in app.module.ts, like this:

@NgModule({
    declarations: [ /* ... */ ],
    imports: [
        MyModule.forRoot('the configuration string') // <- here
    ],
    providers: [/* ... */],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

But I don't want to pass a hardcoded string. Instead I want to retrieve its value from a configuration object fetched from my backend server before app initialization, then declared as an extraProvider when calling platformBrowserDynamic, like this:

// main.ts
Env.getConfig$().subscribe(config => {
    platformBrowserDynamic([
      { provide: AppConfig, useValue: config } // <- here
    ]).bootstrapModule(AppModule)
});

I know that the config can be injected in a service with this configuration (I tested it):

export class AnyService {

  constructor(
    private config: AppConfig
  ) {
    console.log(config); // <- Displays the expected config object
  }
}

My issue is that I want to access this injected configuration object when importing MyModulein the AppModule. Something like:

@NgModule({
    declarations: [ /* ... */ ],
    imports: [
        MyModule.forRoot(config.stringParamValue) // <- How to inject the AppConfig instance?
    ],
    providers: [/* ... */],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

I thought about something involving a forRoot static method in AppModule, that would inject the AppConfig token using an @Inject decorator... but it's seems a little hacky somehow...

I'd also like to avoid storing my config in some kind of global variable in the subscribe callback of the Env.getConfig$ observable.

Thanks in advance for any help!

回答1:

Try define an injection token inside the module (MyModule in this case). And try using like this :

    // main.ts
Env.getConfig$().subscribe(config => {
    platformBrowserDynamic([
      { provide: YourToken, useValue: config } // <- here
    ]).bootstrapModule(AppModule)
});

api doc sample implementation



标签: angular