在Angular应用程序中加载远程配置文件

问题描述 投票:0回答:1

应用程序:我的角度应用程序托管在Nginx服务器上。该应用程序使用两个不同的API服务器,都在NodeJS / express上托管。

问题:两个API服务器的主机名和端口在我的REST服务中的Angular应用程序中静态定义。

export class AppREST {

    primary_api_server_hostname: string = "https://hostname_1:port_1"
    secondary_api_server_hostname: string = "https://hostname_2:port_2"

    //using the above hosts for API
}

应用程序设计的方式是两个API服务器都可以具有不同的主机名和端口名,这些名称和端口名可以与Nginx服务器本身的主机名不同。

预期:一旦使用ng build --prod构建角度应用程序并将生成的文件放在nginx服务器的html文件夹中,就应该有一个选项来动态配置应用程序使用的主机名和端口。

我想找到使用外部json文件动态配置的最佳方法。

我尝试将hosts.json文件直接放在nginx服务器中,该文件在初始化REST API之前已被读取。

这工作正常但只能被视为一种解决方法,因为使用角度CLI ng serve的应用程序的开发变得一团糟。

是否有Angular团队推荐的解决方案?

angular rest nginx angular-http angular-httpclient
1个回答
0
投票

因此,您希望创建一个服务,在Angular应用程序引导时初始化并从JSON文件加载变量。

您需要创建一个加载配置的服务,并在您的应用程序引导时运行:

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

@Injectable()
export class AppConfigService {
    private appConfig;

    constructor (private injector: Injector) { }

    loadAppConfig() {
        let http = this.injector.get(HttpClient);

        return http.get('/assets/app-config.json')
        .toPromise()
        .then(data => {
            this.appConfig = data;
        })
    }

    get config() {
        return this.appConfig;
    }
} 

致谢:How To Use Run-Time Environment Variables In Angular

© www.soinside.com 2019 - 2024. All rights reserved.