Angular 5 中使用一些配置文件的完全外部常量

Kir*_* Ch 7 constants file angular

我有一个带有服务器 URL的app-const.ts:

export class AppConst {
  public static serverPath = 'http://10.0.0.126:3031';
}
Run Code Online (Sandbox Code Playgroud)

这是 Spring Boot REST 服务器的 URL 路径。在这种情况下,我将这个常量放在一个地方,并在所有模块中使用它。但是 ,在构建之后,如果服务器 URL 发生更改,我将无法在不重新构建整个项目的情况下更改此常量。

有什么方法可以将这个常量保存在主机上的某个外部配置文件中(在 index.html 旁边),以便我可以在不重建项目的情况下更改它(比如Spring Boot 中的application.properties文件,谁知道)?

或者我如何通过更改服务器 URL 轻松管理这种情况?

另外。清除情况:我将我的 Angular 网络客户端放在主机上。然后这个客户端开始与可以放置在某处(例如在云中)的 Spring Boot REST 服务器通信。这个 Spring Boot 服务器有一个服务器 URL (serverPath),有时可能会更改。现在,如果服务器 URL 更改,我需要更改此 serverPath 常量并仅由于此常量而重建整个 Angular 项目。

Kir*_* Ch 5

我有以下解决方案。它使用外部 JSON 配置文件。

所以首先在assets/data 文件夹中创建一个 JSON 。

配置文件:

{“服务器路径”:“ http://10.0.0.126:3031 ”}

然后阅读并解析它。

config.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';

@Injectable()
export class ConfigService {

  private configUrl = "assets/data/config.json";

  constructor(private http: HttpClient) {
  }

  public getJSON(): Observable<any> {
    return this.http.get(this.configUrl)
  }

  public getSavedServerPath(){
    return localStorage.getItem('serverPath');
  }
}
Run Code Online (Sandbox Code Playgroud)

在 app.module.ts 中,您需要导入 HttpClientModule 以使其正常工作。

然后您可以在登录组件中将 serverPath 保存在 LocalStorage 中。

登录.component.ts:

  constructor(public loginService:LoginService, public configService:ConfigService, private router: Router) {
  }

  ngOnInit() {

    this.configService.getJSON().subscribe(data => {
      localStorage.setItem("serverPath", data["serverPath"]);
    });

    ...
  }
Run Code Online (Sandbox Code Playgroud)

之后,您可以访问所有其他服务中的 serverPath。

server.service.ts:

import {Injectable } from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
import {ConfigService} from '../services/config.service';

@Injectable()
export class ServerService {

  private serverPath:string;

  constructor(public configService: ConfigService, private http:Http) {
    this.serverPath = this.configService.getSavedServerPath();
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

构建完成后,您将在dist文件夹中看到assets/data/config.json文件。将所有dist文件夹复制到您的主机和所有作品。