Angular 2:引导前的外部配置-将值传递给AppModule [英] Angular 2: External configuration befor bootstrap - passing the value to AppModule

查看:75
本文介绍了Angular 2:引导前的外部配置-将值传递给AppModule的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从外部json文件配置我的Angular 2应用程序.

I am would like to configure my Angular 2 App from external json file.

在我的 main.ts 中,加载 config.json

getHttp().get('/config.json')
         .map(response => response.json();)
         .subscribe(
           data => {
             let clientConf: ClientConfig = data;

             // here I want to pass clientConf to AppModule
             platformBrowserDynamic().bootstrapModule(AppModule);

          });

我想知道如何将 clientConf 传递给AppModule以在 app.module.ts 中使用:

I wonder how to pass clientConf to AppModule to use in app.module.ts:

@NgModule({
     ...
    providers: [
          { provide: Configuration, useValue: clientConf }
           ...

推荐答案

这是我的解决方案:

....
.subscribe(
       data => {
         let clientConf: ClientConfig = data;

         // here I want to pass clientConf to AppModule
          platformBrowserDynamic(
                [{ provide: ClientConfig, useValue: clientConf }]
                ).bootstrapModule(AppModule);

      });

我没有将 clientConf 传递给 AppModule ,我将 platformBrowserDynamic的 ClientConfig 设置为 extraProvider .

I didn't pass clientConf to AppModule, I set ClientConfig as extraProvider for platformBrowserDynamic instead.

然后,如果要使用 ClientConfig ,只需将其注入:

Then if you want to use ClientConfig, just inject it:

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

   constructor(private clientConfig: ClientConfig) { }
   .....

这篇关于Angular 2:引导前的外部配置-将值传递给AppModule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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