角度服务注入(异步)无法正常工作

时间:2015-05-18 19:09:28

标签: angularjs

我想在另一项服务中使用存储在一项服务中的数据。

问题:数据检索的回调函数似乎是异步的,我不能将我的方法应用于检索到的数据。

什么数据检索看起来像

app.factory('userService', ['$http', 'rootUserService', function ($http, rootUserService) {
  var user = null;
  var rootUser;

  return {
    getUser : function(userId) {
      var that = this;

      rootUserService.getUser().then(function(data) {
        that.rootUser = data;
        console.log(data) // working
      });
      console.log(that.rootUser) // undefined
      console.log(rootUser) // undefined

      // Do some stuff with rootuser (another async call & compare users)
    }
  }
}]);

从以下位置检索数据:

app.factory('rootUserService', ['$http', '$rootScope', function($http, $rootScope) {
  var user = null;
  return {
    makeRequest: function(url) {
      var that = this;
      return $http.get(url).then(function (res) {
        return res.data;
      });
    },

    // This is what is used for retrieval
    getUser: function() {
      if(!this.user) { this.user = this.makeRequest('/api/user/get'); };
      return this.user;
    }
  }
}]);

1 个答案:

答案 0 :(得分:0)

服务中的getUser()方法应该返回要解析的promise。像这样:

app.factory('rootUserService', ['$http', '$rootScope', function($http, $rootScope) {
  var user = null;
  return {
    makeRequest: function(url) {
      var that = this;
      return $http.get(url).then(function (res) {
        return res.data;
      });
    },

    // This is what is used for retrieval
    getUser: function() {
      if(!this.user) { 
       return this.makeRequest('/api/user/get').then(function(resp) {
           this.user=data;
           return data;
        }); 
      };
      return this.user;
    }
  }
}]);

app.factory('userService', ['$http', 'rootUserService', function ($http, rootUserService) {
  var user = null;
  var rootUser;

  return {
    getUser : function(userId) {
      var that = this;

      return rootUserService.getUser().then(function(data) {
        that.rootUser = data;
        console.log(data) // working
        // Do some stuff with rootuser (another async call & compare users)
        //All of those actions MUST BE IN HERE
      });
    }
  }
}]);