我正在尝试将一个变量从一个类型脚本文件导入另一个。
我要导入的变量是cityListUrl
它所在的类型脚本文件是这样编码的:
export class backendUrls{
// root url
rooturl:string= 'http://127.0.0.1:8000';
//get a list of all cities
cityListUrl:string = this.rooturl + '/api/city/';
}
我要将其导入的文件如下所示:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {backendUrls} from 'app/backendUrls';
@Injectable()
export class cityGetService{
constructor(private http: Http){}
cityGet(){
this.http.get(backendUrls.cityListUrl)
}
}
我的pycharm编辑器中的cityListUrl
目前是红色的。与消息
TS2339: 'cityListUrl' does not exist on type 'typeof backendUrls'.
有没有人遇到过这个问题?我将如何解决这个问题?谢谢
最佳答案
处理服务器 api url 的最佳方法是使用 Angular 环境文件。 使用它有两个好处:
- 在您的所有应用程序中可用
- 您可以在不修改代码的情况下处理多个平台(localhost、dev、stating、prod)
在 app/environments
中你可以创建不同的文件:
- environments.prod.ts
- 环境.ts
- 环境.test.ts
在每个文件中你定义你的 gobals 变量:
对于本地主机:
export const environment = {
production: false,
apiHost: 'http://localhost',
recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
fileHost: 'http://file.localhost',
};
产品示例:
export const environment = {
production: true,
apiHost: 'http://prod',
recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
fileHost: 'http://file.prod',
};
要在您的脚本中使用它,您只需要始终导入
从'./environments/environment'导入{环境};//你的文件所在的相对路径
import { environment } from './environments/environment'
export class Service {
protected cityListUrl = '/api/city/';
constructor(protected http: Http) { }
get() {
this.http.get(environment.apiHost + this.cityListUrl).map(response => response.json());
}
}
当你使用 angular-cli 构建你的项目时,你需要确定你想要使用哪个环境
ng build --environment=prod
或
ng serve --environment=test
这很酷,因为您可以轻松地将此命令行集成到持续集成工具中。
关于angular - 将变量从一个 typescript 文件导入另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44723184/