如何在AngularJS应用程序中同步加载数据

rya*_*zec 3 angularjs

现在我知道,由于javascript的执行方式,建议您将所有远程请求作为异步而不是同步运行.虽然我同意99%的时间,但有时您确实希望将远程请求作为同步而不是异步运行.例如,加载会话数据是我想要同步进行的操作,因为我不希望在加载数据之前呈现任何视图.这个plunker显示异步加载会话数据的问题(注意:我使用$ timeout来模拟异步调用会发生什么):

http://plnkr.co/edit/bzE1XP23MkE5YKWxRYrn?p=preview

data属性不会加载任何内容,因为数据在尝试获取数据时不可用而data2只是因为数据在尝试获取数据时可用.现在,在这种情况下,我可以将会话变量放在范围上并完成它,但情况并非总是如此.

除了使用jQuery的.ajax()方法(试图尽可能少地依赖jQuery)之外,有没有更好的方法在角度应用程序中同步远程调用?

Joh*_*ter 7

如果您希望在加载控制器之前加载会话数据,则应将其作为resolve参数包含(假设您正在使用$routeProvider).

例如:

angular.module('mymodule', ['ngResource'])

  /* here's our session resource.  we can call Session.get() to retrieve it. */
  .factory('Session', ['$resource', function($resource) {
     return $resource('/api/session.json');
   }])

  /* here's our controller + route definition. */
  .config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/foo', {
      controller: 'MyCtrl',
      templateUrl: '/templates/foo.html',

      /* the controller will not be loaded until the items
       * below are all resolved! */
      resolve: {
        session: ['$q', 'Session', function($q, Session) {
          var d = $q.defer();
          Session.get(function(session) {
            /* session returned successfully */
            d.resolve(session);
          }, function(err) {
            /* session failed to load */
            d.reject(err);
          });
          return d.promise;
        }]
      }
    });
  }])

  .controller('MyCtrl', ['$scope', 'session', function($scope, session) {
    /* 'session' here is the key we passed to resolve above.
     * It will already be loaded and resolved before this function is called */
    $scope.session = session;
  }]);
Run Code Online (Sandbox Code Playgroud)