如何在运行时更改NgModule配置

如何在运行时更改NgModule配置

本文介绍了如何在运行时更改NgModule配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些模块可以公开其服务配置,例如:

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

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

如何在运行时重新配置其中之一?例如,用户选择两个链接之一,并且不同的模块被延迟加载并以不同的方式配置...如何将数据传递到此新的NgModule?

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 :)

推荐答案

创建注射器后无法修改提供程序.

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

然后像使用它

class MyComponentOrService {
  constructor(provider:ProviderService) {}

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

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

这篇关于如何在运行时更改NgModule配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:48