【问题标题】:Reload dynamically JSON of configuration in AngularJS在 AngularJS 中动态重新加载配置的 JSON
【发布时间】:2018-07-04 14:10:11
【问题描述】:

是否可以动态重新加载我的项目的配置?

现在配置文件被 NPM build 缩小了,编辑一个缩小的文件并不容易。

我的配置在appConfig.js 中,其中包含如下代码:

const appConf = {
    BASE_URL: 'http://demo:1817',
    API_BASE_URL: 'http://demo:1817/api'    
};

export default appConf;

在我的index.js 中有这样的代码:

import appConf from "./appConf";

angular.module('app', [])
    .constant('appConf', appConf)
    .run(function(){
        //do something
    });

在我的服务中,我使用这样的配置:

$http.get(appConf.API_BASE_URL + "/something").then(resp => { 
            //do someelse
        });

我想在不运行 NPM 构建的情况下使用 API 的新 URL 编辑 appConfig.js

我想这样做是因为在演示环境中 URL 会经常更改。

【问题讨论】:

    标签: javascript angularjs json node.js


    【解决方案1】:

    在angular2中编辑最小化文件非常困难,不推荐。 获取基本 url 并使用它而不是保存在配置中。请尝试以下任何一种。 下面是Angular2的代码

    在服务中添加以下方法

    hostUrl() {
          var hostName = window.location.origin;
          return hostName + '/';
      }
    

    在 ts 文件中使用如下

    this.http.get(this.service.hostUrl() + "/something" {
        //do someelse
        });
    

    import {LocationStrategy } from '@angular/common';
    
    constructor(private locationStrategy:LocationStrategy) {
            let currentUrl = this.locationStrategy.path();
            currentUrl = currentUrl.substring(0, currentUrl.indexOf('?'));
            console.log('currentUrl '+currentUrl);
            this.http.get(currentUrl + "/something" {
            //do someelse
            });
    }
    

    【讨论】:

    • 是的,但我在 angularJS 中,我需要设置不同的 URL
    • 如果我们使用 maven,我们可以在 pom.xml 中设置 dev、stage 和 prod 等配置文件。处理这种情况会更好。如果您使用 maven 没有问题,我将分享那段代码
    猜你喜欢
    • 2019-04-26
    • 2022-01-08
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多