AngularJS - 绕过$http承诺的对象管理



我有这样的服务:

angular.module('module')
.factory('UserList', function ($http) {
    return {
        getUserList: $http.get('/portal-services/NemesysPortalBackend/rest/user/all')
    };
 });

这限制了我做

UserList.getUserList.then(function(res){$scope.data = res.data;})

在我需要它的每个控制器中。有没有办法"门面"它简单地拥有

$scope.data = UserList.getUserList();

谢谢

我在这里假设用户列表不经常更改,因此您可以将其缓存到变量中...否则,每次您希望列表更改时都需要进行调用(或使用间隔重新加载列表?

在真正需要之前获取数据称为"预先加载"

angular.module('module').factory('UserList', function ($http, $q, $interval) { // import $q as well
    var userList = []; // initialized as blank array
    var refreshList = function(){
        var deferred = $q.defer();
        $http.get('/portal-services/NemesysPortalBackend/rest/user/all').then(
            function(successResponse){
                userList = successResponse.data;
                deferred.resolve(successResponse);
            },function(failureResponse){
                // do something on error?
                deferred.reject(failureResponse);
            });
        return deferred.promise;
    } 
    refreshList(); // eager load, run right away
    // i don't recommend this next line, there are better ways of doing this
    $interval(refreshList(), 1000*60); // get new list every 60 seconds

    return {
        getUserList: function(){ return userList; }, // return user list only
        refreshList: function(){ refreshList(); } // return promise which getting new list
    };
 });

同样,我不建议使用 $interval 来重新加载列表,而是在对用户列表进行更新时调用 refreshList

前任:

angular.module('module').controller('userCtrl', function(UserList) { 
    $scope.data = UserList.getUserList();
    // once you change the user list, call a refresh
    UserList.addUser().then(UserList.refreshList()).then(function(){
         $scope.data = UserList.getUserList();
    );

});

你不能这样做,因为JavaScript是单线程的。这意味着,当您使用某些异步调用时,您永远无法使其同步。Javascript中没有等待(*)。不能阻止函数调用以等待来自服务器的结果。

即使你像这样努力:

function getResult() {
   var result;
   UserList.getUserList.then(function(res) {
       result = res.data; // this should break the loop below
   });
   while (!result) {}; // active waiting, wasting CPU cycles
   return result;
}

。它不起作用,因为在当前运行的代码(即无限循环)完成之前不会执行回调函数。像这样的无限循环将永远冻结整个应用程序。


(*) 这并不意味着您不能安排稍后调用的函数。承诺和关闭对此有很大帮助。

最新更新