How to change NgModule configuration at runtime

情到浓时终转凉″ 提交于 2019-12-04 22:28:19

问题


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

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

How would I reconfigure one of these at runtime? For example, user selects one of two links and different module is lazy loaded and configured differently... How can I pass data to this new NgModule?

All I can think of is to put something in global scope and read it from there, but... doesn't feel right :)


回答1:


Providers can't be modified after the injector was created.

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

@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();
  }
}


来源:https://stackoverflow.com/questions/40032954/how-to-change-ngmodule-configuration-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!