我想在具有 WebAPI 端点的 Angular 2(这是一个普通的 TypeScript 文件)中加载常量文件。 在 Angular1.x 中。我们曾经有相同的常数。 我如何在 Angular 2 中实现相同的功能?
我已经创建了 .ts 文件。我主要关心的是如何在每个其他类文件加载之前加载该文件。
.ts 文件:
export class testAPI {
getAPI = "myUrl";
}
在服务文件中,我通过正常导入使用相同的文件:
constructor(private http: Http) {
//console.log(this.test);
console.log(this.testing.getAPI);
//this.test.load();
}
我将控制台设置为未定义。(一定是因为我的服务类在 API 类之前加载)。
提前致谢。
最佳答案
更新
受此特定问题解决方案的启发 ngx-envconfig打包并将其发布在 NPM 注册表上。它具有与此答案中提供的功能相同的功能,甚至更多。
您可以将 JSON 文件放在 Assets 文件夹中的某个位置,例如:assets/config
。根据环境是否为开发环境,您可以使用两个 .json
文件,一个用于开发,一个用于生产。因此,您可以拥有 development.json
和 production.json
文件,其中每个文件都将保留适当的 API 端点。
基本上您需要完成以下步骤:
1。设置环境(已有环境可跳过)
在 src/environments
文件夹中创建两个文件:
environment.prod.ts
export const environment = {
production: true
};
environment.ts
export const environment = {
production: false
};
2。创建 JSON 配置文件
assets/config/production.json
{
"debugging": false,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
assets/config/development.json
{
"debugging": true,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
3。创建服务如下
注意根据环境,ConfigService
将加载适当的文件
import { Injectable, APP_INITIALIZER } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
import { environment } from 'environments/environment'; //path to your environment files
@Injectable()
export class ConfigService {
private _config: Object
private _env: string;
constructor(private _http: Http) { }
load() {
return new Promise((resolve, reject) => {
this._env = 'development';
if (environment.production)
this._env = 'production';
console.log(this._env)
this._http.get('./assets/config/' + this._env + '.json')
.map(res => res.json())
.subscribe((data) => {
this._config = data;
resolve(true);
},
(error: any) => {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
});
});
}
// Is app in the development mode?
isDevmode() {
return this._env === 'development';
}
// Gets API route based on the provided key
getApi(key: string): string {
return this._config["API_ENDPOINTS"][key];
}
// Gets a value of specified property in the configuration file
get(key: any) {
return this._config[key];
}
}
export function ConfigFactory(config: ConfigService) {
return () => config.load();
}
export function init() {
return {
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}
}
const ConfigModule = {
init: init
}
export { ConfigModule };
4。与 app.module.ts 集成
import { NgModule } from '@angular/core';
import { ConfigModule, ConfigService } from './config/config.service';
@NgModule({
imports: [
...
],
providers: [
...
ConfigService,
ConfigModule.init(),
...
]
})
export class AppModule { }
现在,您可以在任何需要的地方使用 ConfigService,获取在配置 .json
文件中定义的必要 API 端点。
关于json - 在 Angular 2 中加载配置 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42110817/