假设我的服务从 $resource get 返回一个承诺,我想知道这是否是缓存数据的正确方法。在这个例子中,在点击返回箭头并返回搜索结果后,我不想再次查询网络服务器,因为我已经有了它们。这是处理这种情况的正确模式吗?下面的示例是查询 Flixter (Rotten Tomatoes) Api。
精简代码:
控制器:
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 密钥。