Javascript 如何避免多次执行来自服务的查询(get)?

Javascript 如何避免多次执行来自服务的查询(get)?,javascript,angularjs,caching,Javascript,Angularjs,Caching,我提供的服务如下所示: var chatServices = angular.module('chatServices', ['ngResource']); chatServices.factory('Chat',['$resource', function($resource){ return $resource('sample-chat-data.json', {}, { query: {method:'GET', params:{}, isArray:true}

我提供的服务如下所示:

var chatServices = angular.module('chatServices', ['ngResource']);

chatServices.factory('Chat',['$resource',
  function($resource){
    return $resource('sample-chat-data.json', {}, {
      query: {method:'GET', params:{}, isArray:true}
    });
  }
]);
我有两个控制器,一个用于主视图,一个用于详细视图:

  chatListApp.controller('ChatItemsController', ['$scope', 'Chat', "$location",
    function ($scope, Chat, $location) {
      $scope.chatitems = Chat.query();
      $scope.detailPage = function (hash) { 
        $location.path(hash);
      }
    }]);

  chatListApp.controller('ChatDetailController', ['$scope', "$routeParams", "Chat",
    function ($scope, $routeParams, Chat) {
      $scope.chatID = $routeParams.chatID; 
      $scope.chatitems = Chat.query(function() { 
        for (var i = 0; i < $scope.chatitems.length; i++) { 
          if ($scope.chatitems[i].id === $scope.chatID) { 
            $scope.chat = $scope.chatitems[i]; 
            break; 
          } 
        };
      });
    }]);
我觉得我的代码远远不是最优的,原因是我做了两次相同的查询。有没有一个聪明的方法可以做到这一点?我是否可以将服务结果保存/缓存到变量中

您可以在那里看到SPA的完整代码和在线工作示例:

打开缓存

chatServices.factory('Chat',['$resource',
  function($resource){
    return $resource('sample-chat-data.json', {}, {
      query: {method:'GET', params:{}, isArray:true,cache : true}
    });
  }
]);

因此,将返回结果保存在变量中不是一个选项?实际上,使用变量进行保存并不准确,因为对于保存请求,我们已经有了chache标志,为什么不使用它呢这对我来说是一个更简单、更美好的方式