Angular工厂承诺的可变范围

时间:2014-07-11 09:18:07

标签: javascript angularjs angularjs-scope angular-promise

我无法将数据从工厂中的Angular承诺返回到控制器。 在这个例子中,

http://jsfiddle.net/c3xjE/

update: function (staffList) {
    // get local last updated timestamp
    var lastUpdatedLocal = "";
    var lastUpdatedRemote = "";
    for (i=0; i < staffList.length; i++) {
        // get largest (most recent) timestamp
        if(staffList[i].entry_date > lastUpdatedLocal) {
            lastUpdatedLocal = staffList[i].entry_date;
        }
    }

// get remote last updated timestamp
var promise = $http.get('REMOTE_API_CALL')
    .success(function(data, status, header, config) {
        return lastUpdatedRemote = data[0].entry_date;
    }).then(function(response) {
        return response.data[0].entry_date;
        });
    console.log(promise);
}

我想过滤本地数据以获取本地时间戳,将其与远程时间戳进行比较,并指示控制器在本地时间戳小于远程时间戳的情况下重新下载所有数据。

我正好过滤本地数据并获得预期结果。我似乎陷入困境的地方是承诺。我可以在.success或.then方法中注销已过滤的远程数据,但是没有多少运气从承诺中返回值。我知道这里可能存在变量范围的问题。

另外,我最好将一个布尔值从我的工厂返回到我的控制器(我应该更新吗?是/否)或者可能是一个带有本地&amp;的小obj。远程加时间戳数据并让控制器决定从那里做什么?

提前致谢。

1 个答案:

答案 0 :(得分:2)

以下是我如何实现这一点的最佳示例。我假设了一些关于你的控制器和工厂的东西。请注意,您需要向工厂注入$ q以使用延迟。这是我在我的应用程序中执行此操作的方式。

http://jsfiddle.net/JimTheDev/2zLEp/

/*
  NOTE: make sure to inject $q into your factory before
  this. For the purposes of my example, let's assume your
  factory looks like this:
*/
app.factory('mySweetFactory', ['$q', function($q) {
    return {

        // You probably have a bunch of other methods like
        // this one in your factory.
        myothermethod: function(argument1, argument2) { 
            /* some code here */
        },

        update: function (staffList) {

            // Create a new deferred object
            var deferred = $q.defer();

            // get local last updated timestamp
            var lastUpdatedLocal = "";
            for (i=0; i < staffList.length; i++) {
                // get largest (most recent) timestamp
                if(staffList[i].entry_date > lastUpdatedLocal) {
                    lastUpdatedLocal = staffList[i].entry_date;
                }
            }

            // Make a call to the remote api
            $http.get('REMOTE_API_CALL').then(function(response) {

                // Get the remote last updated
                // time from the response
                var lastUpdatedRemote = response.data[0].entry_date;

                // Check if local or remote is larger
                // You probably need to modify this 
                // depending on your datetime formatting. 
                // I am assuming an epoch string.
                if(lastUpdatedRemote > lastUpdatedLocal)
                {
                    // Resolve the deferred and return
                    // the data so that the controller can
                    // use it to update the view
                    deferred.resolve(response.data);
                } else {
                    // Since we don't need to do anything,
                    // reject the deferred
                    deferred.reject();
            });

            // Return the promise from the deferred object
            // immediately. We will eventually either 
            // resolve or reject it, but at the start, it
            // will be in a pending state.
            return deferred.promise;
        }
    };
}]);

app.controller('mySweetController', ['mySweetFactory', function(mySweetFactory){
    $scope.doUpdate = function() {
        mySweetFactory.update($scope.staffList).then(function(newStaffList) {
            // Promise was resolved. List needs updating!
            $scope.staffList = newStaffList;
        }, function(){
            // Promise was rejected. No update needed!
        });
    };
}]);