解决角度js中的承诺并将其设置为另一个工厂

时间:2017-06-12 15:29:18

标签: javascript angularjs angular-promise

我有一个以下工厂

.factory('UserData', ['User', '$q', function(User, $q) {
    var deferred = $q.defer();

    return {
        user: null,
        get: function() {
            var _this = this;
            _this.user = User.get();
            deferred.resolve(User.get());
            return deferred.promise();
        }

    };

}]);

我的用户工厂中有一些数据,User.get()将重新启动数据。 我需要从分配给此user: null

的UserData工厂中重新获取此数据

1 个答案:

答案 0 :(得分:0)

Solution:

.factory('UserData', ['User', '$q', function(User, $q) {
   var _factory = {};

   _factory.user = null;

   /* returns a promise that resolves to user value */
   _factory.get = function() {
     // return cached user as a resolved promise
     if (_factory.user) return $q.resolve(_factory.user);

     return User.get().then(function(user) { // chain User.get() promise
       return _factory.user = user; // cache user value in _factory.user
     });
   };

   return _factory;
}]);

I'm assuming you want to use a cached version (just return value if factory.user is populated already). You can just remove the caching part if that's not the case.

Also, I don't know if you'd want to expose the user variable as part of the factory. If that's not the case you might just want to declare it as a variable instead (and change _factory.user references as well) to hide internal implementation details.