Angular,如何在生产和开发环境之间切换?

时间:2017-11-17 15:07:35

标签: angular environment production

我有一个很大的Angular应用程序,在开发中仍然需要,但已经准备好在生产中使用,我希望通过简单的更改来切换状态

isProduction: boolean = false

为真, 我通过制作apiHelperService来做到这一点,它只是常用的服务,它适用于大多数应用程序:

import {Injectable} from "@angular/core";
import {Response, Http, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class ApiHelperService {
  productionURL: string = 'http://35.203.121.40';
  developmentURL: string = 'http://10.25.37.523';
  serverUrl: string;
  apiPort: string = ':3000/';
  socketPort: string = ':2000/';
  isProductionMode: boolean = false;


  constructor() {
    this.serverUrl = this.isProductionMode ? this.productionURL : this.developmentURL;
  }

  getApiURL(): string {
    return this.serverUrl + this.apiPort;
  }

  getSocketUrl(): string {
    return this.serverUrl + this.socketPort;
  }
  getApiIp(): string {
    const serverIp = this.isProductionMode ? this.productionURL.split(':')[0] : this.developmentURL.split(':')[0];
    console.log('string url is:', serverIp);
    return serverIp;

  }
  serialize(obj) {
    var str = [];
    for (var p in obj) {
      if (obj.hasOwnProperty(p) && ((obj[p] != null && obj[p] != '') || (typeof obj[p] == "boolean"))) {
        if (obj[p].length == 0) {
          continue;
        }
        else if (obj[p].length > 1 && typeof obj[p] == 'object') { // reformats arrays
          for (let i = 0; i < obj[p].length; i++) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
          }
        }
        else {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
      }
    }

    return '?' + str.join("&");
  }

  extractData(res: Response) {
    let body = res.json();
    // console.log("body", body)
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

但我有套接字库,用于在

中配置套接字URL
  

app.module.ts

所以当我尝试使用动态URL(在app.module.ts中)时,这样:

const apiHelper = new ApiHelperService(); //fails here
const url: string = apiHelper.getSocketUrl();
const config: SocketIoConfig = { url: url, options: {
  "force new connection" : true,
  "reconnectionAttempts": "Infinity",
  "timeout" : 10000,
  "transports" : ["websocket"]} };

它因此错误而失败:

ERROR in Error: Error encountered resolving symbol values statically. Calling 
function 'ApiHelperService', function calls are not supported. Consider replacing the function or lambda with a
reference to an exported function, resolving symbol AppModule

所以我的问题是,我的做法是错的吗? 处理这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

它的工作方式不同:alligator.io/angular/environment-variables

您必须在 environment.ts environment.prod.ts

中指定变量

然后从&#39; ../../ environment / environment&#39;; 导入{environment} 环境对象将包含适当的变量