【问题标题】:Cache Data with $resource promises pattern使用 $resource 承诺模式缓存数据
【发布时间】:2013-04-21 08:32:05
【问题描述】:

假设我的服务从 $resource get 返回一个承诺,我想知道这是否是缓存数据的正确方法。在这个例子中,在点击返回箭头并返回搜索结果后,我不想再次查询网络服务器,因为我已经有了它们。这是处理这种情况的正确模式吗?下面的示例是查询 Flixter (Rotten Tomatoes) A​​pi。

简化代码:

控制器:

function SearchCtrl($scope, $route, $routeParams, $location, DataService) {
    DataService.search($routeParams.q).then(function(data){
       $scope.movies = data.movies;
    });
}

服务:

angular.module('myApp.services', []).
 factory('DataService', ['$q', '$rootScope', 'JsonService', function ($q, $rootScope, JsonService) {

  var movie = {};
  var searchResults = {};
  var searchq = '';
  var service = {

    search: function(q) {

        var d = $q.defer();
        // checking search query, if is the same as the last one, 
        //resolve the results since we already have them and don't call service
        // IS THIS THE CORRECT PATTERN
        if (q==searchq) {
           d.resolve(searchResults);              
        } else {
          // returns a $resource with defined getdata
          JsonService.search.movieSearch(q, 20, 1).getdata(function(data){
            searchResults = data;
            searchq = q;
            d.resolve(searchResults);
          });
        }
       return d.promise;

    },
      getSearchResults: function() {
        return searchResults;
      }
 };

 return service;
 }]);

我无法提供一个可行的示例,因为它会暴露我的 API 密钥。

【问题讨论】:

    标签: angularjs angular-resource


    【解决方案1】:

    我伪造了实际的 ajax 请求,但我认为一般的想法应该适用,你可以看到 full demo here

    这里是控制器,它只是执行搜索然后设置结果:

    myApp.controller('MyCtrl', function($scope, DataService) {
         $scope.search = function(){
              DataService
                  .search($scope.q)
                  .then(function(response){
                      $scope.fromCache = response.fromCache;
                      $scope.results = response.results;
                  });
          };
    });
    

    在 DataService 中,我只是将结果保存到一个键控查询的对象中。这很简单,但希望能帮助您入门。如果你想要这样的东西,你可以将它保存在 html5 存储或其他东西中。

    您需要在此处输入实际的 ajax 调用,但原则仍然存在。

    myApp.factory('DataService', function($q){
          var resultsCache = {};
          return {
              search: function(query){
                  var deferred = $q.defer();
                  if (resultsCache[query]) {
                      resultsCache[query].fromCache = true;
                  }
                  else {
                      resultsCache[query] = {results: [{name: 'result one'}, {name: 'result two'}]};
                  }
                  deferred.resolve(resultsCache[query]);
                  return deferred.promise;
              }
          };
    });
    

    希望有帮助

    【讨论】:

    • 谢谢,很好的解决方案。使用 localStorage 甚至像 taffyDB 这样的东西可能是一个有趣的解决方案。我会等着看我是否得到更多的答案,然后奖励它。
    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 2015-06-20
    • 2014-04-29
    • 2014-11-20
    • 2015-08-29
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多