1. 程式人生 > >Ionic在應用程式啟動前讀取應用程式啟動之前的配置檔案,避免程式碼頻繁編譯

Ionic在應用程式啟動前讀取應用程式啟動之前的配置檔案,避免程式碼頻繁編譯

1.app.module.ts
在這裡插入圖片描述

2.app.config.ts
1.新建app.config.ts檔案
2.內容:

import { Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AppConfig {

    private config: Object = null;
    private env:    Object = null;

    constructor(private http: Http) {

    }

    /**
     * Use to get the data found in the second file (config file)
     */
    public getConfig(key: any) {
        return this.config[key];
    }

    /**
     * Use to get the data found in the first file (env file)
     */
    public getEnv(key: any) {
        return this.env[key];
    }

    /**
     * This method:
     *   a) Loads "env.json" to get the current working environment (e.g.: 'production', 'development')
     *   b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
     */
    public load() {
        return new Promise((resolve, reject) => {
            this.http.get('env.json').map( res => res.json() ).catch((error: any):any => {
                console.log('Configuration file "env.json" could not be read');
                resolve(true);
                return Observable.throw(error.json().error || 'Server error');
            }).subscribe( (envResponse) => {
                this.env = envResponse;
                let request:any = null;

                switch (envResponse.env) {
                    case 'production': {
                        request = this.http.get('config.' + envResponse.env + '.json');
                    } break;

                    case 'development': {
                        request = this.http.get('config.' + envResponse.env + '.json');
                    } break;

                    case 'default': {
                        console.error('Environment file is not set or invalid');
                        resolve(true);
                    } break;
                }

                if (request) {
                    request
                        .map( res => res.json() )
                        .catch((error: any) => {
                            console.error('Error reading ' + envResponse.env + ' configuration file');
                            resolve(error);
                            return Observable.throw(error.json().error || 'Server error');
                        })
                        .subscribe((responseData) => {
                            this.config = responseData;
                            resolve(true);
                        });
                } else {
                    console.error('Env config file "env.json" is not valid');
                    resolve(true);
                }
            });

        });
    }
}

3.env.json
在你將配置當前開發環境的地方。允許的值是“development”和“production”
{ "env": "development" }
4.config.development.json
這是你將編寫生產配置變數的地方。您可以在JSON檔案中新增您想要的變數。
{ "host": "測試地址" }
5.config.production.json
這是你將編寫生產配置變數的地方。您可以在JSON檔案中新增您想要的變數。
{ "host": "正式釋出地址" }
ps:位置參考
在這裡插入圖片描述
6.根據配置讀取相應的地址
***1.***我這裡寫了公共方法,所以在公共方法裡直接調AppConfig的方法,獲取地址即可
service-base.ts(公共方法)


在這裡插入圖片描述
結束

***2.***或者將讀取配置檔案單獨寫在一個.ts檔案,即把***1***拆分
2.1:app.commont.ts

   import { Injectable, Inject } from "@angular/core";
    import { AppConfig } from '../../app/app.config'
   @Injectable()
   export class AnyClass {
         constructor(private config: AppConfig) {
    }
    myMethodToGetHost() {
        return this.config.getConfig('host');
    }
}

2.2service-base.ts(公共方法)
在這裡插入圖片描述

結束
本篇內容參考:https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
感謝