我有一个大的 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);
}
}
但是我有套接字库,可以在
中配置套接字 URLapp.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
所以我的问题是,我的方法错了吗? 处理这个问题的正确方法是什么?
最佳答案
它以不同的方式工作:alligator.io/angular/environment-variables
您必须在 environment.ts 和 environment.prod.ts 中指定变量
然后从'../../environments/environment'导入{environment}; 环境对象将包含适当的变量
关于Angular,如何在生产环境和开发环境之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47353706/