javascript - 值未设置为 JS/AngularJs 中的全局变量

标签 javascript angularjs gulp angular-services angular-factory

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

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 的调用,这是不正确的。

我可以在其他任何地方获取新的设置值,但该值并未以某种方式在资源服务对象中设置。 我肯定错过了一些东西。

任何帮助将不胜感激

最佳答案

由于您正在使用 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' ]);

要使用该变量,您必须在提供程序中注入(inject):

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
            }
        });
}

关于javascript - 值未设置为 JS/AngularJs 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46896606/

相关文章:

javascript - AngularJS 格式 JSON 字符串输出

javascript - 脚本的大小(外部链接)+将它们合并为 1

npm - Gulp:我需要 package.json 吗?

angularjs - 根据 ui-grid 中的 cellTemplate 设置 csv 导出格式

angularjs - 无法找到指令 'ngMessages' 所需的 Controller 'ngMessage'

node.js - 无法安装 gulp-sass

javascript - 在 react 中进行函数调用之前如何设置状态?

javascript - Ionic 带有地理位置警报 : 'mySecondApp.app/www/index.html' Would like to use your current location

javascript - 从浏览器使用 tampermonkey 或 greasemonkey 更改 ip

javascript - 在 Firefox 和 ie/edge 上使用 openlayers 3 未加载 map