gpt4 book ai didi

javascript - 如何发出多个http请求?

转载 作者:行者123 更新时间:2023-12-03 10:11:01 25 4
gpt4 key购买 nike

我的父 Controller 和子 Controller 中有一个 HTTP 请求:

父 Controller

//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.
})

子 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;
})

当我进入某些页面时,子 Controller 会启动。问题是当我启动这些页面时,代码将向 api/url 发出双重 http 请求,因为父 Controller 和子 Controller 都会发出请求。虽然我的应用程序仍然可以运行,但我想知道是否有更好的方法来解决它。感谢您的帮助!

最佳答案

编辑:我稍微研究了菲尔的评论,并修复(重写)了我的示例。底部的小图标反射(reflect)了这些变化。这是更新后的代码:

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 分离到工厂并将值存储在那里。工厂是单例的,因此两个 Controller 都可以访问和检查数据。

JS:

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;
})
}
}
}
})

它只是运行检查以查看该值是否已存储,如果已存储则返回它,如果没有,则获取、存储并返回它。

Plunker

关于javascript - 如何发出多个http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30115767/

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