gpt4 book ai didi

javascript - 如何防止请求重复?

转载 作者:行者123 更新时间:2023-11-29 14:43:15 27 4
gpt4 key购买 nike

我有一个 Controller CounterpartyCtrl 被两个 View 使用。

第一个 View 包含一个选择器,它需要集合中的所有记录。所以我获取所有对象并将它们放入 $scope.counterparties

     app.controller('CounterpartyCtrl', [
'$scope', 'Counterparty', function($scope, Counterparty) {},
$scope.counterparties = {},

$scope.loadCounterparties = function() {
Counterparty.query(function(response) {});
$scope.counterparties = response;
},

$scope.loadCounterparties();

]);

第二个 View 必须只包含按组划分的交易对手。

  $scope.customers
$scope.vendors
$scope.others
$scope.HRs

所以,使用相同的 Controller ,我像下面这样获取它们

 app.controller('CounterpartyCtrl', [
'$scope', 'Counterparty', function($scope, Counterparty) {},
$scope.counterparties = {},

$scope.loadCounterparties = function() {
Counterparty.query(function(response) {});
$scope.counterparties = response;

$scope.customers = Counterparty.query({
group: 'Customer'
});

$scope.vendors = Counterparty.query({
group: 'Vendor'
});

$scope.others = Counterparty.query({
group: 'Other'
});

$scope.HRs = Counterparty.query({
group: 'HR'
});
},

$scope.loadCounterparties();

]);

正如您在此处看到的,显然是重复的请求。在每一个观点上,我都提出了平等的要求,因此那是没有成效的。如何重构代码?

最佳答案

我的意思是使用 $q 并将结果缓存在服务中以避免多次请求:http://plnkr.co/edit/3AeOjHaVo8MrY18tStEs

app.factory("dataService", ["$http","$q", function($http, $q){
var counterParties;
return {
query: function(param){
if(!counterParties){
counterParties = $q.defer();
$http.get("requestURL").then(function(response){
counterParties.resolve(response.data);
});
}
return counterParties.promise;
}
};
}]);

关于javascript - 如何防止请求重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35854325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com