I am having a problem with promises in an angular service. I have a service with a method getArea
which is supposed to return the name of a service-area. The service gets the service-areas from the API. When getArea
gets the service-areas, it finds the name of the requested area, and should return it. However, my code does not work - I get into an infinite loop. I guess I have misunderstood how to use 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
I expect the view to show "Area: hello world", but gets into an infinite loop.
Update 1: I have added getServices
as a public function in the service, and can access it from the controller like this:
SupplierService.getServices().then(function(d){
$scope.services = d;
});
Therefore I guess the problem is in the getArea
method?
Update 2: I was inspired by this answer https://stackoverflow.com/a/12513509/685352. I want to cache the result.
Update 3: Here is a plunker. If you try accessing supplierService.getArea(100)
from the view - the browser will not respond.