Sampath Sampath - 3 months ago 7
AngularJS Question

Before resolving the promise on service method,it goes to the main method's promise

I have written Angular Service as shown below.

getPropertyDetailsByUsingApiService.js

(function () {
appModule.service('getPropertyDetailsByUsingApiService', ['$http', function ($http) {
this.propertyDetails = function (token, number, street, county, zip) {
var endpointUrl = 'http://my.com/api/Matcher?Token=';
var url = endpointUrl + token + '&Number=' + number + '&Street=' + street + '&County=' + county + '&Zip=' + zip;

return $http.get(url).then(function (data) {
var result = data;
if (result.data[0].Status == 'OK') {
$http.get(endpointUrl + token + '&Krp=' + result.data[0].Result[0].KRP + '&County=' + county)
.then(function (finalData) {
return finalData;
});
}
});
};
}
]);
})();


This is the consuming method :

propertyForm.js

//to call Api
vm.callApi = function () {
var county = _.find(vm.counties, function (c) { return c.id == vm.property.countyId; });
var city = _.find(vm.cities, function (c) { return c.id == vm.property.address.cityId; });

getPropertyDetailsByUsingApiService.propertyDetails(vm.getMd5Hashbytes(), vm.property.address.streetNumber, vm.property.address.streetName,
county.name, city.zipCode).then(function (result) {
vm.propertyDetails = result;
});
};


Q : Issue here is before resolving the promise on service method,it goes to the main method's promise.In other words before resolving 2nd promise on the service method where it goes to the calling method's promise.Can you tell me where is the issue ?

Answer

You can rewrite:

return $http.get('url').then(function(r) => { return r;})

as:

var defer = $q.defer();

$http.get('url').then(function(r) => { defer.resolve(r);})

return defer.promise;

It does not make sense in usual case, but in special cases, you can do whatever with this construction:

var defer = $q.defer();
if (smth) {
    defer.resolve('test1');
} else {
    $http.get('url').then(function(r) => {
        if (smth2) { 
            defer.resolve(r);
        } else {
            $http.get(..., function(r) => {
                defer.resolve(r);
            })
        }
    })
|

return defer.promise;
Comments