Angular:构建后是否可以读取json文件 [英] Angular: Is it possible to read a json file after building
问题描述
我正在研究一个Angular 7项目,该项目需要在不同的服务器上运行.我需要从环境文件中读取服务器URL,并且无法将其设置为静态变量.
I am working on an angular 7 project which needs to be running on different servers. I need to read server URL from environment file and cannot set as a static variable.
我尝试读取JSON文件,但是当我 ng构建项目后,它就将JSON的内容复制为main.js中的静态值
I tried reading a JSON file but as soon as I ng build the project, it copies the content of JSON as static value in main.js
构建项目后是否可以动态读取JSON文件?就像从env.json中读取内容一样,我可以在构建项目后将其放入
Is it possible to read a JSON file dynamically after building the project? Like reading from env.json which I can put after building the project
推荐答案
借助Hien Ngyuen的回答,我做到了:
With the help of Hien Ngyuen's answer, I did this:
添加了以下服务:
config.service.ts
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import { ConstantService } from './constant.service';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
constructor(
private httpService: HttpService,
private constantService: ConstantService
) { }
/*
* Load configuration from env.json
*/
loadConfig(): Observable<any> {
let url = './assets/env.json';
let requestObject = {
API_URL: url,
REQUEST_METHOD: this.constantService.REQUEST_METHOD_GET
};
return this.httpService.sendRequest(requestObject).pipe(map(this.extractData));
}
/*
* Extract data from response
*/
private extractData(res: Response) {
let body = res;
return body || {};
}
}
http.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ConstantService } from './constant.service';
const httpOptions = {
withCredentials: true,
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(
private httpClient: HttpClient,
private constantService: ConstantService
) { }
sendRequest(requestData) {
if (requestData.REQUEST_METHOD == this.constantService.REQUEST_METHOD_GET) {
return this.httpClient.get(url, httpOptions);
} else if (requestData.REQUEST_METHOD == this.constantService.REQUEST_METHOD_POST) {
return this.httpClient.post(url, requestData.BODY, httpOptions);
} else if (requestData.REQUEST_METHOD == this.constantService.REQUEST_METHOD_PUT) {
return this.httpClient.put(url, requestData.BODY, httpOptions);
} else if (requestData.REQUEST_METHOD == this.constantService.REQUEST_METHOD_DELETE) {
return this.httpClient.delete(url, httpOptions);
}
}
}
接下来,在 ng构建之后,我添加了 assets \ env.json ,并且能够更改和读取来自env.json的值.
Next, after ng build I added assets\env.json and I was able to change and read values from env.json.
这篇关于Angular:构建后是否可以读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!