How to change NgModule configuration at runtime

There are some modules that disclose their service configuration, for example:

  • AngularFireModule.initializeApp(firebaseConfig),
  • StoreModule.provideStore(reducer),
  • RouterModule.forRoot(routes)...

How do I reconfigure one at runtime? For example, the user selects one of two links, and the other module is lazy loaded and configured differently ... How to transfer data to this new NgModule?

All I can think of is to put something in the global realm and read it from there, but ... I don't feel good :)

+4
source share
1 answer

Providers cannot be changed after the creation of the injector.

You can create a service that provides different instances depending on the state.

@Injectable()
class ProviderService {
  constructor(injector:Injector) {}

  set firebaseConfig(firebaseConfig) {
    let resolvedProviders = ReflectiveInjector.resolve([AngularFireModule.initializeApp(firebaseConfig)]);
    this.childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);    
  }

  get firebase ():AngularFireModule {
    return this.childInjector.get(AngularFireModule);
  }
}

and then use it like

class MyComponentOrService {
  constructor(provider:ProviderService) {}

  changeFirebase() {
    this.provider.firebaseConfig = ...;
    this.fb = this.provider.firebase;
  }

  doSomething() {
    this.fb.xxx();
  }
}
+2

Source: https://habr.com/ru/post/1657691/


All Articles