我试图将一个变量从一个类型脚本文件导入到另一个。
我要导入的变量是 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/';
}
Run Code Online (Sandbox Code Playgroud)
我想将其导入的文件如下所示:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
在cityListUrl目前我pycharm编辑器是红色的。随着消息
TS2339: 'cityListUrl' does not exist on type 'typeof backendUrls'.
Run Code Online (Sandbox Code Playgroud)
以前有人遇到过这个问题吗?我将如何解决这个问题?谢谢
处理服务器 api url 的最佳方法是使用 Angular 环境文件。使用它有两个好处:
您app/environments可以创建不同的文件:
在每个文件中,您定义了 gobals 变量:
对于本地主机:
export const environment = {
production: false,
apiHost: 'http://localhost',
recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
fileHost: 'http://file.localhost',
};
Run Code Online (Sandbox Code Playgroud)
对于产品示例:
export const environment = {
production: true,
apiHost: 'http://prod',
recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
fileHost: 'http://file.prod',
};
Run Code Online (Sandbox Code Playgroud)
要在脚本中使用它,您只需要始终导入
import { environment } from './environments/environment'; //relative path from where your file is
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());
}
}
Run Code Online (Sandbox Code Playgroud)
当您使用 angular-cli 构建项目时,您可以精确确定要使用的环境
ng build --environment=prod
或者
ng serve --environment=test
这很酷,因为您可以轻松地将这个命令行集成到持续集成工具中。
| 归档时间: |
|
| 查看次数: |
10122 次 |
| 最近记录: |