![](/img/trans.png)
[英]Calling http request from success of previous http response (avoiding callback hell) in Angular 4
[英]Angular JS $http request - caching success response
我有一个简单的dataFactory可以检索一些帖子:
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 ......
});
但是,我现在正在尝试缓存发布数据-但是,当第二次调用控制器时,它将返回错误。成功不是函数。 我认为是因为帖子已经被退回-但是我该如何处理呢?
那是因为您没有返回$http.get
,而是在已经处理了.success
和.error
之后返回了.success
。
您可以将控制器更改为在返回时调用.then
,也可以将服务更改为仅返回$http.get
(删除.success
和.error
)并在控制器中进行处理。
如果更改控制器使用.then
你还需要更新.success
在服务功能return posts;
。
您是否尝试过在$http
调用中将cache
选项设置为true? 像这里https://stackoverflow.com/a/14117744/1283740
也许是这样的...
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;
}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.