Encountering an issue with promises within an angular service. The problem lies with a specific method getArea
in the service which aims to retrieve the name of a service area. This data is obtained from the API. However, upon obtaining the service areas and trying to fetch the requested area's name, the code falls into an infinite loop. It seems there might be a misunderstanding regarding the usage of promises?
SupplierService:
var servicePromise;
var getServices = function(){
if( !servicePromise ){
servicePromise = $http.get('/api/services')
.then(function(res){
return res.data.data;
});
}
return servicePromise;
};
var myService = {
getServices : getServices,
getArea : function(questionnaireId){
getServices().then(function(services){
// ...
return "hello world";
});
}
};
return myService;
Controller:
$scope.supplierService = SupplierService;
View:
<div>
<b>Area:</b> {{ supplierService.getArea(r.questionnaireId) }}
</div
The expected result in the view is "Area: hello world", but instead, it remains stuck in an infinite loop.
Update 1: A public function getServices
has been added to the service, accessible from the controller like this:
SupplierService.getServices().then(function(d){
$scope.services = d;
});
Hence, the issue likely resides within the getArea
method?
Update 2: Took inspiration from this response . Intending to cache the outcome.
Update 3: Sharing a plunker. Trying to access supplierService.getArea(100)
from the view renders the browser unresponsive.