我在父控制器和子控制器中有一个HTTP请求:
父控制器
//Product is a $resource object that return http request as a promise.
Product.getItem()
.then(function(items) {
$scope.items = items
//do something in the parent controller.
})
子控制器
Product.getItem()
.then(function(items) {
$scope.items = items
//do something in the child controller
})
产品工厂
angular.module('testApp').factory('Product', function($http,$q) {
var service = {}
service.getItem = function() {
return http.$get('api/url');
}
return service;
})
子控制器是启动时,我在某些页面。问题是,当我启动这些页面时,代码会向api/url发出双重的http请求,因为父控制器和子控制器都会发出请求。虽然我的应用程序仍然有效,但我想知道是否有更好的方法来解决它。谢谢你的帮助!
发布于 2015-05-07 21:33:54
编辑:--我研究了一下菲尔的评论,修正了(重写)我的例子。底部的柱塞反映了这些变化。以下是更新的代码:
app.controller('MainCtrl', function($scope, getStore) {
getStore.get().then(function(data) {
$scope.data = data
})
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
$timeout(function() {
getStore.get().then(function(data) {
$scope.test = data
})
},3000)
});
app.factory('getStore', function($http, $q) {
var self = this;
var data;
return {
get: function() {
if (data) {
console.log(data);
console.log('already got data')
return $q.when(data)
} else {
data = $http.get('test.json')
.then(function(response) {
console.log('fetched data')
return response.data;
})
return data
}
}
}
})
这里有一个解决方案--将您的$http.get分离到一个工厂,并将值存储在那里。工厂是单机,所以两个控制器都可以访问和检查数据。
联署材料:
app.controller('MainCtrl', function($scope, getStore) {
$scope.data = getStore.get()
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
$timeout(function() {
$scope.data = getStore.get()
var check = getStore.checkData();
console.log('Data in store: ' + angular.toJson(check));
},1000)
$scope.getData = function() {
console.log(getStore.get());
}
});
app.factory('getStore', function($http) {
var self = this;
return {
data: undefined,
get: function() {
if (self.data) {
console.log('already got data')
return self.data
} else {
$http.get('test.json')
.success(function(data) {
console.log('no data found');
self.data = data;
console.log(self.data);
return self.data;
})
}
}
}
})
它只是运行一个检查,看看该值是否已经存储,然后返回它如果是,如果不是,它得到,存储,并返回它。
https://stackoverflow.com/questions/30115767
复制相似问题