【问题标题】:Angular, how to switch between production and development environments?Angular,如何在生产和开发环境之间切换?
【发布时间】:2018-05-01 09:51:48
【问题描述】:

我有一个大型 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

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

【问题讨论】:

  • 你在用cli吗?
  • 我不太明白,我用 'ng serve' 启动应用程序并用 'ng build ...' 部署它
  • 你在用什么 Angular cli 进行开发
  • 我使用“ng new my-app”构建了应用程序,但据我了解,我没有对配置文件进行任何更改,现在,所有更改都在 Angular 应用程序中进行,并且Build 版本与开发版本相同,只是将 false 更改为 true(在 Angular 服务中)
  • 是否有您无法从环境文件中读取 isProduction 布尔值的原因? (例如,创建一个 environment.development.ts 和一个 environment.production.ts)例如:alligator.io/angular/environment-variables

标签: angular environment production


【解决方案1】:

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

您必须在 environment.tsenvironment.prod.ts

中指定变量

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

【讨论】:

  • 链接 alligator.io/angular/environment-variables 添加
猜你喜欢
  • 1970-01-01
  • 2018-06-04
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多