现在我知道,由于 javascript 的执行方式,建议您将所有远程请求作为异步而不是同步运行。虽然我同意 99% 的时间,但有时您确实希望将远程请求作为同步而不是异步运行。例如,加载 session 数据是我想要同步执行的操作,因为我不希望在加载该数据之前呈现任何 View 。这个 plunker 显示了异步加载 session 数据的问题(注意:我使用 $timeout 来模拟异步调用会发生什么):
http://plnkr.co/edit/bzE1XP23MkE5YKWxRYrn?p=preview
data 属性不加载任何内容,因为在尝试获取数据时数据不可用,而 data2 加载只是因为在尝试获取数据时数据可用。现在在这种情况下,我可以将 session 变量放在作用域上并完成它,但情况并非总是如此。
除了使用 jQuery 的 .ajax() 方法(尽量少依赖 jQuery)之外,有没有更好的方法在 Angular 应用程序中同步远程调用?
最佳答案
如果您希望在加载 Controller 之前加载 session 数据,则应将其作为 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;
}]);
关于angularjs - 如何在 AngularJS 应用程序中同步加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731942/