Javascript AngularJS$http.get发送相同的xhr请求两次
在我的应用程序中,我正在使用 在我的服务中,我有下一个代码:Javascript AngularJS$http.get发送相同的xhr请求两次,javascript,angularjs,ajax,angular-ui-router,Javascript,Angularjs,Ajax,Angular Ui Router,在我的应用程序中,我正在使用 在我的服务中,我有下一个代码: function ResourceService($http, AppSettings) { 'ngInject'; const service = {}; service.getResource = function(params) { console.log('Get resource') return new Promise((resolve, reject) =>
function ResourceService($http, AppSettings) {
'ngInject';
const service = {};
service.getResource = function(params) {
console.log('Get resource')
return new Promise((resolve, reject) => {
$http.get(AppSettings.apiUrl + 'v1/resorce')).then((resp) => {
resolve(resp);
}).catch((err, status) => {
reject(err, status);
});
});
};
在控制器中:
function ResourceCtrl(BidService) {
'ngInject';
// ViewModel
const vm = this;
ResourceService.getResource().then((res) => {
vm.items = res.data;
});
}
export default {
name: 'ResourceCtrl',
fn: ResourceCtrl
};
在开发人员控制台中:
如何防止查询重复?默认情况下
$http
返回承诺。因此,您不需要再次创建承诺来解决它。只需返回服务的请求并解决控制器的承诺
service.getResource = function(params) {
console.log('Get resource')
return $http.get(AppSettings.apiUrl + 'v1/resorce'))
};
控制器
ResourceService.getResource()
.then((res) => {
vm.items = res.data;
}).catch((res) => {
console.log(res.data)
});
这并不能防止xhr重复。请您仔细检查查看中仅提到过一次的
ResourceCtrl
?也许它可以从路由配置中再次加载(只是猜测)。ResourceCtrl从配置(ui路由器)中加载一次,但它将用作嵌套控制器FE:account account.resources-->xhr 1次。account.resources.resource-->xhr 2次。