如何在AngularJS应用同步加载数据加载、数据、如何在、AngularJS

2023-09-13 03:27:51 作者:一个人想着一个人

现在我所知道的,因为JavaScript的执行,建议您运行所有的远程请求的异步,而不是同步的方式。虽然我用的时间99%的人同意,有时候你想要运行的同步,而不是异步远程请求。例如,装载会话数据是我会想要做的共时,因为我不希望有任何意见渲染,直到数据被加载。这plunker显示了asynchronically加载会话数据(注:我使用$超时模拟将与一个异步调用发生什么):这个问题

Now I know that because of the way javascript executes it is recommended that you run all remote requests as async instead of sync. While I agree with that 99% of the time, sometimes you do want to run remote request as a sync instead of a async. For example, loading session data is something I would want to do synchronically as I don't want any views to render until that data is loaded. This plunker shows the issue with loading session data asynchronically (NOTE: I am using $timeout to simulate what would happen with an async call):

http://plnkr.co/edit/bzE1XP23MkE5YKWxRYrn?p=$p$ PVIEW

,因为当它试图得到它,​​只是因为数据是可​​用的,当它试图得到它DATA2确实的数据不可用的数据属性不加载任何东西。现在,在这种情况下,我可能只是把会话变量的范围和用它做但事实并非总是如此。

The data property does not load anything because the data is not available when it tries to get it and data2 does only because the data is available when it tries to get it. Now in this case I could just put the session variable on the scope and be done with it but that is not always the case.

有没有更好的办法做到在一个应用程序的角度比使用jQuery的阿贾克斯()方法(试图依靠jQuery的尽可能少)?

Is there a better way to do sync remote calls in an angular application other than using jQuery's .ajax() method (trying to depend on jQuery as little as possible)?

推荐答案

如果您希望会话数据之前要加载控制器加载,你应该包括它作为为解析参数(假设你正在使用的 $ routeProvider )。

If you want the session data to be loaded prior to a controller being loaded, you should included it as as resolve parameter (assuming you are using the $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;
  }]);