我正在使用Angularjs发送多个http请求。
我们可以为一些请求设置优先级吗?
我一直在发送http请求根据我的需要。我不能按顺序发送请求http请求
我们是否可以设置的优先级
任何想法?
谢谢
嘿,我建议你使用http拦截器服务,你可以监控每个请求和响应,就像这样,这只是一个想法
.factory('httpInterceptor', function ($q, $rootScope, $filter) {
var canceller = $q.defer();
var numLoadings = 0;
var serialRequests = false;
var timeO;
var time1;
var loadingbar = { loading: "<progress value='?' max='10'></progress>" };
var loadingspinner = { loading: '<ion-spinner icon="crescent"></ion-spinner>' };
return {
request: function (config) {
if (config.url.indexOf('http') > -1 && config.url.indexOf('UpdateDeviceOnlineState') == -1 && config.url.indexOf('maps.googleapis') == -1) {
console.log(config);
//timeout if request takes longer than 15 sec spinner is removed request is cancelled and alert is called
//config.timeout = canceller.promise;
//var time1 = setTimeout(function () {
// canceller.resolve('Unauthorized');
// $rootScope.$broadcast("all_requests_done");
// alert('keine verbindung');
//}, 15000);
numLoadings++;
if (serialRequests == false) {
//if (config.url.indexOf('http') > -1) {
// loadingbar.percent = numLoadings;
// $rootScope.$broadcast("open_requests", loadingbar);
//} else {
// $rootScope.$broadcast("open_requests", loadingspinner);
//}
$rootScope.$broadcast("open_requests", loadingspinner);
} else {
clearTimeout(timeO);
}
}
return config || $q.when(config)
},
response: function (response) {
if (response.config.url.indexOf('http') > -1 && response.config.url.indexOf('UpdateDeviceOnlineState') == -1 && response.config.url.indexOf('maps.googleapis') == -1) {
//clearTimeout(time1);
serialRequests = true;
numLoadings--;
timeO = setTimeout(function () {
serialRequests = false
if ((numLoadings) === 0) {
$rootScope.$broadcast("all_requests_done");
}
});
}
return response || $q.when(response);
},
responseError: function (response) {
if (response.config.url.indexOf('http') > -1 && response.config.url.indexOf('UpdateDeviceOnlineState') == -1 && response.config.url.indexOf('maps.googleapis') == -1) {
serialRequests = true;
numLoadings--;
timeO = setTimeout(function () {
serialRequests = false
if ((numLoadings) === 0) {
$rootScope.$broadcast("all_requests_done");
}
});
}
return $q.reject(response);
}
};
})
但我认为你必须在这里与承诺合作。$http有一个timeout属性,你可以用它来对你的请求进行优先级/排序