角度服务:存储后未检索到数据

时间:2015-05-15 18:39:47

标签: angularjs angular-ui-router

我正在学习角度,我正在尝试使用服务来存储来自HTTP请求的数据,并且以后能够访问它。

问题: 每次我尝试检索数据对象时它都是空的,这会导致它进行新的调用。我在ui-router resolve的上下文中使用它(这会导致服务重新实例化并丢失数据)吗?

服务:

evaApp.factory('userService', ['$http', '$q', function ($http, $q) {
  var user = {};
  return {

    makeRequest   : function(url, uid) {
      var deferred = $q.defer();

      if (!uid) { uid = ''; };

      $http.get(url, { params : { userId : uid } }).then(function (res) {
        deferred.resolve(res.data);
      });

      return deferred.promise;
    },

    getUser       : function(userId) {
      console.log(user); // user is always empty
      if(!user || !user._id) { 
        user = this.makeRequest('/api/user/get', userId);
      };

      return user;
    }
  }
}]);

增加:

数据存储正在使用PSL的解决方案。数据检索不是:Link to question.

2 个答案:

答案 0 :(得分:1)

DB::select("(SELECT SUM(payments.amount) as pay from payments")[0]->pay 返回一个promise,它没有this.makeRequest属性,导致它再次进行ajax调用(由于条件为_.id)。只需从getUser返回promise本身并使用它。请记住,您不是通过执行if(!user || !user._id) {

来分配用户而是分配承诺

而是只做: -

user = this.makeRequest('/api/user/get', userId);

并在make request中执行:

var user = {};
getUser : function(userId) {
  return user[userId] || (user[userId] = this.makeRequest('/api/user/get', userId)
                .catch(function(){ user = null })); //nullify in case of error for retry

}

在从控制器拨打电话时你会这样做: -

makeRequest   : function(url, uid) {

  if (!uid) { uid = ''; };

  return $http.get(url, { params : { userId : uid } }).then(function (res) {
    return res.data;
  });
},

注意:当您已经有一个返回承诺的操作时,请避免使用deferred anti-pattern

答案 1 :(得分:0)

你可以做这样的事情:

evaApp.factory('userService', ['$http', '$q', function ($http, $q) {
  var user = {};
  return {

    makeRequest   : function(url, uid) {
      var deferred = $q.defer();

      if (!uid) { uid = ''; };

      $http.get(url, { params : { userId : uid } }).then(function (res) {
        user = res.data;
        deferred.resolve(user);
      });

      return deferred.promise;
    },

    getUser       : function(userId) {
      console.log(user); // user is always empty
      if(!user || !user._id) { 
        return this.makeRequest('/api/user/get', userId);
      };

      var deferred = $q.defer();
      deferred.resolve(user);
      return deferred.promise;
    }
  }
}]);

然后获取这样的用户详细信息(1仅用于示例):

userService.getUser(1).then(
   function( data ) {
      console.log(data);
   }
);