值未在JS / AngularJs中设置为全局变量

时间:2017-10-23 18:57:48

标签: javascript angularjs gulp angular-services angular-factory

我正在使用gulp来运行和构建以运行我的应用程序。我在$http文件中使用index.js服务获取文件内容,然后设置变量值

window.variablex = "http://localhost:8080/appname"

这是我在做什么(在index.js

(function ()
 {
  'use strict';

   angular
    .module('main')
    .controller('IndexController', IndexController);
function IndexController($http){
   $http.get('conf/conf.json').success(function(data){

     window.variable = data.urlValue;

  }).error(function(error){
    console.log(error);
  });
    }
});

我已经创建了一个工厂来调用后端应用程序的其余API,如

(function(){

  'use strict';

   angular
   .module('main')
   .factory('testService',['$resource',testService]);
     function agentService($resource){
 var agents = $resource('../controller/',{id:'@id'},
  {

    getList:{
      method:'GET',
      url:window.variable+"/controller/index/",
      isArray:false
}
});

现在,除了休息电话,我就像

一样

http://localhost:8080/appname/controller

但是它总是发送一个像http://undefined/appname/controller这样的调用,这是不正确的。

我可以在其他地方获取新的设置值,但不会以某种方式在resource service个对象中设置此值。 我肯定错过了一些东西。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

当您使用Gulp时,我建议您使用gulp-ng-config

例如,您有config.json:

{
  "local": {
    "EnvironmentConfig": {
      "api": "http://localhost/"
    }
  },
  "production": {
    "EnvironmentConfig": {
      "api": "https://api.production.com/"
    }
  }
}

然后,gulpfile中的用法是:

gulp.task('config', function () {
    gulp.src('config.json')
        .pipe(gulpNgConfig('main.config', {
            environment: 'production'
        }))
        .pipe(gulp.dest('.'))
});

您将获得此输出:

angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});

然后,您必须在app.js中添加该模块

angular.module('main', [ 'main.config' ]);

要使用该变量,您必须在提供者中注入:

angular
    .module('main')
    .factory('testService', ['$resource', 'EnvironmentConfig', testService]);
function agentService($resource, EnvironmentConfig) {

    var agents = $resource('../controller/', {id: '@id'},
        {

            getList: {
                method: 'GET',
                url: EnvironmentConfig + "/controller/index/",
                isArray: false
            }
        });
}

答案 1 :(得分:0)

@Kenji Mukai的回答确实有效,但我可能不得不在运行时更改配置,但它失败了。这就是我实现它的方式(如果在应用程序获得boostrap之前有任何问题设置变量)

这些是我遵循的套装

  1. ng-app="appName"文件中删除html,因为这是导致问题的原因。 Angular命中此标记并在其他任何内容之前引导您的应用程序。因此,在从服务器端(在我的情况下)加载数据之前,应用程序是引导的
  2. 在我的主模块中添加了以下内容

    var injector = angular.injector(["ng"]);
    var http = injector.get("$http");
       return http.get("conf/conf.json").then(function(response){
        window.appBaseUrl = response.data.gatewayUrl
          }).then(function bootstrapApplication() {
             angular.element(document).ready(function() {
             angular.bootstrap(document, ["yourModuleName"]);
            });
         });
    
  3. 每次刷新页面时都会加载/设置新值。您甚至可以在运行时更改conf.json文件,刷新页面将负责更新值。

相关问题