LoginSignup
11
13

More than 5 years have passed since last update.

Angular2 定数を宣言 / 環境変数の利用

Posted at

背景

サーバサイドアプリケーションでは環境によって動作を切替えたい場合、”環境変数”が利用される。
Angular2でもAPIの振り分けなど、利用したい場面があり、同様の実装ができるか調査した。。

【目的】
AngularJS 1.*では下記でできた様に、APIの接続先を変える実装にしたい。
http://qiita.com/Quramy/items/d460d6859187d3af34c1

グローバル定数の利用

環境変数を利用するためには、まず該当の変数をグローバル定数とする方法を知る必要がある。

これはAppModuleで宣言して、利用するサービスにDIする方法で実現できる。
アプリケーション中で使用したい変数を provideで宣言すれば良い。

下記ではAPI接続先を 'ApiEndpoint'に設定している。

{provide: 'ApiEndpoint', useValue: 'http://localhost:3000/api/v1'}

利用例

app.module.ts
@NgModule({
  providers: [
    appRoutingProviders,
    {provide: APP_BASE_HREF, useValue: '/'},
    {provide: 'ApiEndpoint', useValue: 'http://localhost:3000/api/v1'},
  ],
....
..
})
export class AppModule { }
api.service.ts
import {Injectable, Inject} from '@angular/core';
import { Http, Headers, Request, Response } from '@angular/http';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';

@Injectable()

export class ApiService {

  constructor(
    private _http: Http,
    @Inject('ApiEndpoint') private api_path: string,
    @Inject('AnalyzeEndpoint') private analyze_path: string
  ) {

  }
  <省略>
}

環境変数を設定する

これはどうやらビルド時に工夫するのが一番良さそう。
開発環境と、本番環境で実行するビルド手順を分けて、違う設定ファイルを見るようにする。

たとえば下記のように、同名のファイルにコピーするで続きを環境によって振り分ければ良い。方法は gruntやgulpなど利用してるビルド環境にもよるのでここでは深掘りしないことにする。

開発用 app.setting.dev.js → app.setting.js
本番用 app.setting.js → app.setting.js

利用例は下記に記載

app.settings.dev.ts
export const  API_ENDPOINT = 'http://localhost:3000/api/v1';
app.settings.prod.ts
export const  API_ENDPOINT = 'http://yourapp.com/api/v1';
app.module.ts

import {API_ENDPOINT} from "./settings/app.setting";

@NgModule({
  providers: [
    appRoutingProviders,
    {provide: APP_BASE_HREF, useValue: '/'},
    {provide: 'ApiEndpoint', useValue: API_ENDPOINT}
  ],
  <省略>
})
export class AppModule { }
Gruntfile.js
module.exports = function(grunt) {
  // configure the tasks
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    copy: {
      prod: {
        expand: true,
        cwd: 'app/settings/',
        src: ["app.setting.prod.ts"],
        dest:  'app/settings/',
        rename:function(path,name){
          return path + "app.setting.ts";
        }
      },
      dev: {
          expand: true,
          cwd: 'app/settings/',
          src: ["app.setting.dev.ts"],
          dest: 'app/settings/',
          rename:function(path,name){
            return path + "app.setting.ts";
          }
      }
    },
    <省略>
  }

  //本番用ビルド
  grunt.registerTask(
    'build',[
      'clean:dist',
      'sass:dist',
      'copy:prod',
      'ts:default',
    ]
  );

 //開発用ビルド
 grunt.registerTask(
    'build-dev',[
      'clean:dist',
      'sass:dist',
      'copy:dev',
      'ts:default',
    ]
  );
};

参考記事
http://stackoverflow.com/questions/34986922/define-global-constants-in-angular-2

11
13
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
11
13