角度控制器不等待服务承诺解决

时间:2015-05-13 00:17:42

标签: angularjs angular-promise

我有一个Angular服务,如下所示:

(function () {
'use strict';

var serviceId = 'currentUserService';
angular.module('app').factory(serviceId, ['common', 'datacontext', currentUserService]);

function currentUserService(common, datacontext) {
    var $q = common.$q;
    var getLogFn = common.logger.getLogFn;
    var logError = getLogFn(serviceId, "error");
    var user = {};

    var service = {
        user: user,
        doesUserHaveFeature: doesUserHaveFeature
    };

    activate();

    return service;

    function activate() {
        var promises = [getCurrentUser()];
        $q.all(promises);
    }

    function getCurrentUser() {
        var deferred = $q.defer();
        datacontext.getLoginInformation().then(function (data) {
            user = data;
            deferred.resolve(data);
        });
        return deferred.promise;
    }

    function doesUserHaveFeature(featureName) {
        debugger;
        var feature = featureName.toLowerCase();

        var result = _.filter(user.features, function(item) {
            var featureString = item.toLowerCase();
            return feature == featureString;
        });

        if (result) {
            return true;
        }

        return false;
    }
}

})();

服务注入我的Controller,我的控制器调用doUserHaveFeature()方法。

但是,在解析activate方法中的promise之前,会调用doesUserHaveFeature方法。因此,用户变量仍然是一个空对象。

如何在调用doesUserHaveFeature方法之前确保返回activate方法中的promise?

谢谢! 杰里米

1 个答案:

答案 0 :(得分:3)

由于user数据是异步检索的,因此您的工厂方法必须返回promises。我就是这样做的......

.factory('currentUserService', function(datacontext) {
    var userPromise = datacontext.getLoginInformation();

    return {
        user: userPromise,
        doesUserHaveFeature: function(featureName) {
            return userPromise.then(function(user) {
                return _.some(user.features, function(feature) {
                    return feature.toLowerCase() === featureName.toLowerCase();
                });
            });
        }
    };
});