I recently developed a service for my AngularJS app that retrieves data by making $http
calls through various methods. However, I encountered an issue where these requests were being triggered every time an HTML element in the view (a product details div) became visible in the viewport due to lazy loading. This led to multiple simultaneous requests (approximately 50-60), causing performance degradation and potential blocking of other requests or the entire application. To address this problem, I needed to implement a mechanism to limit, restrict, queue, or delay the requests - with queuing being the preferred solution. For now, I decided to manage the request volume within the service.
This is how I invoke the service in my controllers/directives:
productAvailabilityService.getAvailability(scope.productId).then(function (result) {
// handle the result...
});
Here's the initial service implementation:
.factory('productAvailabilityService', function ($http) {
var prodAv = {};
prodAv.getAvailability = function (productId) {
return $http({
method: 'GET',
url: '/api/product/getAvailability',
params: {
'productId': productId
}
}).then(
function (response) {
return response;
}, function () {
return 0;
});
}
};
return prodAv;
});
Now, I aim to incorporate limiting functionality as follows:
.factory('productAvailabilityService', function ($http) {
var prodAv = {};
prodAv.requests = 0;
prodAv.getAvailability = function (productId) {
if (prodAv.requests > 6) {
return function () {
return 'Too many requests';
};
} else {
prodAv.requests++;
return $http({
method: 'GET',
url: '/api/product/:productId/getAvailability',
params: {
'productId': productId
}
}).then(
function (response) {
prodAv.requests--;
return response;
}, function () {
prodAv.requests--;
return 0;
});
}
};
return prodAv;
});
However, implementing this approach resulted in the error message "getAvailability(...).then is not a function" when the number of requests exceeded 6. I am struggling to resolve this issue. Additionally, I acknowledge that my current method may not be the best way to control the frequency of invoking a service or executing $http
requests. I welcome any suggestions or advice on improving this process. Thank you in advance!