在Angular2应用中,设置一个配置文件config.json

我想使用JSON文件来配置Angular2应用程序,并在部署后通过修改配置JSON来改变应用程序的行为。

实现方法

通过使用APP_INITIALIZER的依赖注入,可以在应用程序初始化期间执行任意处理。

可以预见到在获取设置JSON后,应用程序启动可能需要一段时间,但它可以简单实现。

实施案例

该环境使用 angular-cli@1.0.0-beta.21,angular 2.2.1 和 rxjs@5.0.0-beta.12。

ConfigService用于读取和存储JSON数据。
需要配置文件的组件使用依赖注入(DI)来使用该服务。

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ConfigService {
  config: any;
  constructor(private http: Http) { }

  load() {
    return new Promise((resolve) => {
      this.http.get('config.json')
        .map(res => res.json())
        .subscribe(json => {
          this.config = json;
          resolve();
        });
    });
  }
}

在app.module.ts中,使用APP_INITIALIZER添加处理程序。

@NgModule({
  ...
  providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: configFactory,
      deps: [ConfigService],
      multi: true
    },
  ],
  ...
})

export function configFactory(cs: ConfigService) {
  return () => cs.load();
}

在Angular 2.2.1中,似乎下面这样写useFactory部分也没有问题。

useFactory: (config: ConfigService) => () => config.load(),

如果升级Angular版本或Angular-CLI版本,会出现以下错误,请在useFactory中指定export function。

在静态解析符号值时遇到错误。不支持函数调用。考虑将函数或lambda表达式替换为对导出函数的引用…

请提供更多上下文。直接的翻译可以是“这是在中国人的母语中的意思。”

    • Angular2 load configuration from backend on startup

 

    • What is best way to load json settings from the server?

 

    Angular 2 make it wait service initialization
广告
将在 10 秒后关闭
bannerAds