Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5, pass config data to an imported sub-module

Tags:

module

angular

I have a main module in my library which I can call with forRoot and pass some config data (like seen here Pass config data using forRoot)

export const MODULE_OPTIONS = new InjectionToken<ModuleOptions>('MODULE_OPTIONS');

@NgModule({
  imports: [
    MySubModule.forRoot(//needs access to options)
  ]
})
export class MyModule {
  static forRoot(options: ModuleOptions = {}): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        {
          provide: MODULE_OPTIONS,
          useValue: options
        }
        ]
    }
    }
}

My Submodule now also needs access to the options I provide from outside when importing my Main Module "MyModule" into an application/module.

How can I pass my ModuleOptions I provide in MyModule.forRoot to MySubModule?

like image 547
Arikael Avatar asked Jan 10 '18 07:01

Arikael


1 Answers

I can't find any official way for this scenario, so I find a way but it is a workaround.

You can call the MySubModule.forRoot in the MyModule.forRoot function and assign the providers. (But also you have the import/export the submodule if you have components/directives in the submodule.)

export const MODULE_OPTIONS = new InjectionToken<ModuleOptions>('MODULE_OPTIONS');
    
@NgModule({
   //You don't have to import/export if MySubmodule doesn't have any component/directive declaration.
   imports: [MySubModule],
   exports:[MySubModule]  
})
export class MyModule {
   static forRoot(options: ModuleOptions = {}): ModuleWithProviders {
     //Now we are able to provide services/values that uses options in the MySubmodule.
     const moduleProviders= MySubmodule.forRoot(options).providers;
     moduleProviders.push({provide: MODULE_OPTIONS,useValue: options});
     return {ngModule: MyModule,providers: moduleProviders};
   }
}
like image 77
ierhalim Avatar answered Oct 11 '22 17:10

ierhalim