LoginSignup
7
6

More than 5 years have passed since last update.

Angular2アプリに設定config.jsonを持たせる

Posted at

Angular2アプリの設定をJSONで用意し、デプロイ後に設定JSONを変更することでアプリの動作を変更できるようにしたい。

実現方法

APP_INITIALIZERのDIを利用することで、アプリの初期化中に任意の処理を行うことができます。

若干起動に時間がかかるようになることが予想されますが、設定JSON取得後にアプリが立ち上がるためシンプルに実装できます。

実装例

環境はangular-cli@1.0.0-beta.21で、angular 2.2.1、rxjs@5.0.0-beta.12です。

JSONデータの読み出しと保持するConfigService。
configが必要なcomponentにこのサービスを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を指定しましょう。

Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function ...

参考

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6