我有一个AngularJS服务,我想用一些异步数据初始化它。就像这样:

myModule.service('MyService', function($http) {
    var myData = null;

    $http.get('data.json').success(function (data) {
        myData = data;
    });

    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

显然,这将不起作用,因为如果有人试图在myData返回之前调用doStuff(),我将得到一个空指针异常。就我所知,从阅读这里提出的其他一些问题中,我有一些选择,但没有一个看起来很干净(也许我遗漏了一些东西):

带有“run”的安装服务

当设置我的应用程序这样做:

myApp.run(function ($http, MyService) {
    $http.get('data.json').success(function (data) {
        MyService.setData(data);
    });
});

然后我的服务看起来像这样:

myModule.service('MyService', function() {
    var myData = null;
    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

这在某些时候是有效的,但如果异步数据花费的时间恰好比所有东西初始化所需的时间长,那么当我调用doStuff()时,我会得到一个空指针异常。

使用承诺对象

这可能行得通。唯一的缺点它到处我调用MyService,我必须知道doStuff()返回一个承诺和所有的代码将不得不我们然后与承诺交互。我宁愿只是等待,直到myData返回之前加载我的应用程序。

手动启动

angular.element(document).ready(function() {
    $.getJSON("data.json", function (data) {
       // can't initialize the data here because the service doesn't exist yet
       angular.bootstrap(document);
       // too late to initialize here because something may have already
       // tried to call doStuff() and would have got a null pointer exception
    });
});

全局Javascript Var 我可以将我的JSON直接发送到一个全局Javascript变量:

HTML:

<script type="text/javascript" src="data.js"></script>

data.js:

var dataForMyService = { 
// myData here
};

然后在初始化MyService时可用:

myModule.service('MyService', function() {
    var myData = dataForMyService;
    return {
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

这也可以工作,但我有一个全局javascript变量闻起来很糟糕。

这是我唯一的选择吗?这些选项中是否有一个比其他选项更好?我知道这是一个相当长的问题,但我想表明我已经尝试了所有的选择。任何指导都将不胜感激。


当前回答

基于Martin Atkins的解决方案,这里有一个完整、简洁的纯angular解决方案:

(function() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/config.json').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);

      angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
    }
  );
})();

这个解决方案使用一个自动执行的匿名函数来获取$http服务,请求配置,并在配置可用时将其注入到名为config的常量中。

完成之后,我们等待文档准备好,然后引导Angular应用。

这是对Martin的解决方案的轻微改进,Martin的解决方案将获取配置延迟到文档准备好之后。据我所知,没有理由为此延迟$http调用。

单元测试

注意:我发现当代码包含在app.js文件中时,这种解决方案在进行单元测试时效果不佳。这样做的原因是上述代码在加载JS文件时立即运行。这意味着测试框架(在我的例子中是Jasmine)没有机会提供$http的模拟实现。

我的解决方案是将这段代码移到index.html文件中,这样Grunt/Karma/Jasmine单元测试基础结构就看不到它了,我对此并不完全满意。

其他回答

此外,在执行实际控制节点之前,还可以使用以下技术实现全局发放业务:https://stackoverflow.com/a/27050497/1056679。只是全局解析你的数据,然后在运行块中传递给你的服务。

我使用了类似于@XMLilley所描述的方法,但希望能够使用AngularJS服务(如$http)来加载配置并进一步初始化,而不使用低级api或jQuery。

在路由上使用resolve也不是一个选项,因为我需要这些值作为常量在我的应用程序启动时可用,甚至在module.config()块中。

我创建了一个小的AngularJS应用程序来加载配置,将它们设置为实际应用程序的常量,并引导它。

// define the module of your app
angular.module('MyApp', []);

// define the module of the bootstrap app
var bootstrapModule = angular.module('bootstrapModule', []);

// the bootstrapper service loads the config and bootstraps the specified app
bootstrapModule.factory('bootstrapper', function ($http, $log, $q) {
  return {
    bootstrap: function (appName) {
      var deferred = $q.defer();

      $http.get('/some/url')
        .success(function (config) {
          // set all returned values as constants on the app...
          var myApp = angular.module(appName);
          angular.forEach(config, function(value, key){
            myApp.constant(key, value);
          });
          // ...and bootstrap the actual app.
          angular.bootstrap(document, [appName]);
          deferred.resolve();
        })
        .error(function () {
          $log.warn('Could not initialize application, configuration could not be loaded.');
          deferred.reject();
        });

      return deferred.promise;
    }
  };
});

// create a div which is used as the root of the bootstrap app
var appContainer = document.createElement('div');

// in run() function you can now use the bootstrapper service and shutdown the bootstrapping app after initialization of your actual app
bootstrapModule.run(function (bootstrapper) {

  bootstrapper.bootstrap('MyApp').then(function () {
    // removing the container will destroy the bootstrap app
    appContainer.remove();
  });

});

// make sure the DOM is fully loaded before bootstrapping.
angular.element(document).ready(function() {
  angular.bootstrap(appContainer, ['bootstrapModule']);
});

查看它的运行情况(使用$timeout而不是$http): http://plnkr.co/edit/FYznxP3xe8dxzwxs37hi?p=preview

更新

我建议使用下面Martin Atkins和JBCP所描述的方法。

更新2

因为我在多个项目中需要它,所以我刚刚发布了一个处理此问题的凉亭模块:https://github.com/philippd/angular-deferred-bootstrap

从后端加载数据,并在AngularJS模块上设置一个名为APP_CONFIG的常量:

deferredBootstrapper.bootstrap({
  element: document.body,
  module: 'MyApp',
  resolve: {
    APP_CONFIG: function ($http) {
      return $http.get('/api/demo-config');
    }
  }
});

您可以使用JSONP来异步加载服务数据。 JSONP请求将在初始页面加载期间发出,结果将在应用程序启动之前可用。这样你就不必用冗余的解决方案来膨胀你的路由。

你的html看起来是这样的:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>

function MyService {
  this.getData = function(){
    return   MyService.data;
  }
}
MyService.setData = function(data) {
  MyService.data = data;
}

angular.module('main')
.service('MyService', MyService)

</script>
<script src="/some_data.php?jsonp=MyService.setData"></script>

基于Martin Atkins的解决方案,这里有一个完整、简洁的纯angular解决方案:

(function() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/config.json').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);

      angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
    }
  );
})();

这个解决方案使用一个自动执行的匿名函数来获取$http服务,请求配置,并在配置可用时将其注入到名为config的常量中。

完成之后,我们等待文档准备好,然后引导Angular应用。

这是对Martin的解决方案的轻微改进,Martin的解决方案将获取配置延迟到文档准备好之后。据我所知,没有理由为此延迟$http调用。

单元测试

注意:我发现当代码包含在app.js文件中时,这种解决方案在进行单元测试时效果不佳。这样做的原因是上述代码在加载JS文件时立即运行。这意味着测试框架(在我的例子中是Jasmine)没有机会提供$http的模拟实现。

我的解决方案是将这段代码移到index.html文件中,这样Grunt/Karma/Jasmine单元测试基础结构就看不到它了,我对此并不完全满意。

你看过$routeProvider吗?当(/路径,{解决:{…}?它可以让承诺的方式更简洁:

在你的服务中暴露一个承诺:

app.service('MyService', function($http) {
    var myData = null;

    var promise = $http.get('data.json').success(function (data) {
      myData = data;
    });

    return {
      promise:promise,
      setData: function (data) {
          myData = data;
      },
      doStuff: function () {
          return myData;//.getSomeData();
      }
    };
});

在路由配置中添加resolve:

app.config(function($routeProvider){
  $routeProvider
    .when('/',{controller:'MainCtrl',
    template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        // MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
        return MyService.promise;
      }
    }})
  }):

在所有依赖项解析之前,你的控制器不会被实例化:

app.controller('MainCtrl', function($scope,MyService) {
  console.log('Promise is now resolved: '+MyService.doStuff().data)
  $scope.data = MyService.doStuff();
});

我在plnkr上举了一个例子:http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview