如何在运行时更改 NgModule 配置 [英] How to change NgModule configuration at runtime

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

问题描述

有一些模块暴露了它们的服务配置,例如:

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

  • 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 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆