Javascript Angular JS$http请求-缓存成功响应
我有一个简单的数据工厂,可以检索一些帖子:Javascript Angular JS$http请求-缓存成功响应,javascript,angularjs,ionic,Javascript,Angularjs,Ionic,我有一个简单的数据工厂,可以检索一些帖子: dataFactory.getPosts = function () { if (this.httpPostsData == null) { this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer
dataFactory.getPosts = function () {
if (this.httpPostsData == null) {
this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date")
.success(function (posts) {
})
.error(function (posts) {
console.log('Unable to load post data: ' + JSON.stringify(posts));
});
}
return (this.httpPostsData);
}
控制员打电话给工厂,我知道这些帖子都是承诺——所以有些东西是成功的,有些东西是无论如何都要做的。这个很好用
.controller('CardsCtrl', function($scope, dataFactory,
$ionicSlideBoxDelegate, $stateParams) {
var parentID = $stateParams.parentID;
var keyIDNumber = $stateParams.keyID;
$scope.card = [];
var httpcall = dataFactory.getPosts()
.success(function (posts) {
$scope.card = dataFactory.getChildPosts(parentID, posts, keyIDNumber);
$ionicSlideBoxDelegate.update();
});
// do other stuff ......
});
但是,我现在尝试缓存post数据,但是当第二次调用控制器时,它返回错误。成功不是一个函数。我想这是因为帖子已经被返回了——但是我该如何处理呢?您是否尝试过在
$http
调用中将缓存
选项设置为true?像这里
也许是这样的
angular.module('foo', [])
.factory('dataFactory', ['$http', function($http){
var dataFactory = {
getPosts: getPosts
};
function getPosts(){
var url = "http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date"
return $http({ cache: true, url: url, method: 'GET'})
.error(function (posts) {
console.log('Unable to load post data: ' + JSON.stringify(posts));
});
};
return dataFactory;
}])
这是因为您没有返回
$http.get
,而是在.success
和.error
已经得到处理之后才返回承诺
您可以将控制器更改为调用。然后返回,或者将服务更改为仅返回$http.get
(删除.success
和.error
)并在控制器中处理它们
如果您将控制器更改为使用。那么
您还需要将服务中的.success
功能更新为return posts代码>