重用服务中的数据

Reuse Data From Service

我正在尝试重用我的服务中的数据。基本上,我有两个动作 indexshow books.

在索引中,我(显然)获取了所有书籍并显示,按照惯例,我只获取了给定的记录。但我也想展示相关书籍,为此我想重用索引操作中请求的数据

我的服务是这样的:

angular.module('myapp').factory('book', ['$http', '$q',
  function($http, $q) {

    var values = [];
    var book = {
      getAll: function() {
        var deferred = $q.defer();
        return $http({
          method: 'GET',
          url: '/books.json'
      }).success(function(data, status){
        values = data;
        deferred.resolve(data);
      })
      return deferred.promise;
    },
    get: function(id){
      return $http({
        method: 'GET',
        url: '/books/' + id + '.json'
      })
    },
    getValues: function(){
      return values;
    }
  }
  return book;
}]); 

在我的 ShowBookController 中,我调用了这个函数:

getBook();
function getBook(){
  var promise = book.get(currentBook);
  promise.then(function(book){
    $scope.book = book.data[0];
  })
  console.log(book.getValues())
}

但是 console.log 打印了一个空数组。

我认为您可以将 console.log(book.getValues()) 移到 then 回调中,因为 get 是一个异步 api 调用。

希望对你有所帮助