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

标签 angular file constants

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

export class AppConst {
  public static serverPath = 'http://10.0.0.126:3031';
}

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

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

或者如何通过更改服务器 URL 轻松应对这种情况?

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

最佳答案

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

因此,首先在assets/data 文件夹 中创建一个 JSON。

config.json:

{ "serverPath": "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');
  }
}

In app.module.ts you need to import HttpClientModule so that this works.

然后你可以将serverPath保存在登录组件的LocalStorage中,例如。

login.component.ts:

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

  ngOnInit() {

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

    ...
  }

之后,您可以在所有其他服务中访问 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();
  }
  ...
}

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

关于angular - 使用一些配置文件在 Angular 5 中完全外部常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49903083/

相关文章:

html - node_modules/@angular/flex-layout/extended/typings/style/style.d.ts 中的错误

angular - 如何在导出函数中注入(inject)服务?

angular - 在 Angular 中,如果我导入一个共享模块但只需要其中的一件事,那会不会是一个不必要的巨大导入?

java - exe不运行

删除 R 中的常量列

Ruby - 使用某些函数进行常量初始化会产生 NoMethodError

angular - 捕获 Angular2 中的所有可点击元素?

Java检测文件系统的变化

javascript - 使用 Typescript 将数组写入文本文件并换行

c++ - const 变量的引用运算符 "&"的结果是什么?