I have HTTP service that returns promise to inspection2update.DamageTypeId property and continue to execute further.
HTTP service:
function post(objectTypeId, damageDescription) {
var defer = $q.defer();
$http.post(serviceAddress + "save/" + objectTypeId + "/" + damageDescription).then(function (response) {
defer.resolve(response.data);
});
return defer.promise;
}
Here how I call service in controller:
inspection2update.DamageTypeId = damageTypesService.save(inspection2update.ObjectTypeId, self.dType);
But I need to wait until I get data from service and only after it, to execute further.
For this purpose I use $q service inside $http resolver, but still I get promise from my service and no data.
What do I have to change in my code to make service wait for data?
You are returning a promise which is resolved after the http call has finished fetching the data. The consumer who use this service needs to wait for the promise to resolve and then do something with the data.
Use the then syntax to receive the promise data and execute further:
damageTypesService.save(inspection2update.ObjectTypeId, self.dType).then(function(data) {
inspection2update.DamageTypeId = data;
// rest of execution...
});
P.S - as far as I can see there is no use of $q in your case (unless you want to mingle with the data / make logs, etc...). You can return the $http call as is:
function save(objectTypeId, damageDescription) {
return $http.post(serviceAddress + "save/" + objectTypeId + "/" + damageDescription);
}
Use the best of angular promise with $q
function save (objectTypeId, damageDescription) {
var deferred = $q.defer();
$http({
url: serviceAddress + "save/" + objectTypeId + "/" ,
method: 'POST',
data: damageDescription
})
.success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
And in your controller use .then function
damageTypesService.save(inspection2update.ObjectTypeId, self.dType).then(function(response){
/*use the response here
eg: inspection2update.DamageTypeId = response.id
*/
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With