Angular:构建后是否可以读取json文件

Ash*_*osh 7 angular

我正在开发一个 Angular 7 项目,该项目需要在不同的服务器上运行。我需要从环境文件中读取服务器 URL,并且无法设置为静态变量。

我尝试读取 JSON 文件,但一旦构建项目,它就会将 JSON 的内容复制为 main.js 中的静态值

构建项目后是否可以动态读取 JSON 文件?就像从 env.json 中读取一样,我可以在构建项目后将其放入

Ash*_*osh 2

在 Hien Ngyuen 的回答的帮助下,我这样做了:

添加了以下服务:

配置服务.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 || {};
}
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,在ng build之后,我添加了assets\env.json,并且能够更改和读取 env.json 中的值。