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

How do I avoid a query (get) from a service being executed multiple times?

本文关键字:get 执行 查询 何避免 服务      更新时间:2023-09-26

我有一个服务,看起来如下:

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的在线工作示例:https://github.com/gkatsanos/angular-demo

打开缓存

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