service
(function () {
'use strict';
angular
.module('app.user')
.factory('myService', Service);
Service.$inject = ['$http', 'API_ENDPOINT', '$q'];
/* @ngInject */
function Service($http, API_ENDPOINT, $q) {
var getUserDetails = function (paramData) {
return $q(function (resolve, reject) {
$http.get(API_ENDPOINT.url + '/user/details', paramData).then(function (result) {
if (result.data.success) {
resolve(result.data);
} else {
reject(result.data.msg);
}
});
});
};
var getCountryDetails = function (paramData) {
return $q(function (resolve, reject) {
$http.get(API_ENDPOINT.url + '/country/details', paramData).then(function (result) {
if (result.data.success) {
resolve(result.data);
} else {
reject(result.data.msg);
}
});
});
};
return {
getUserDetails: getUserDetails,
getCountryDetails: getCountryDetails
};
}
})();
controller
(function () {
'use strict';
angular
.module('app.user')
.controller('myService');
/* @ngInject */
function UserCtrl(userService,countryService) {
var vm = this;
vm.onCountryChange = function (id) {
vm.states = vm.countries.filter(function (item) {
return item.id === id;
})[0].states;
};
function init() {
var token = window.localStorage.getItem('TOKEN');
vm.userData = jwt_decode(token);
// fetch all country and its states parallelly
myService.getCountryDetails()
.then(function(msg){
vm.countries = msg.data;
// once both requests are completed, trigger onCountryChange()
Promise.all([myService.getCountryDetails(), myService.getUserDetails(paramData)]).then(values => {
const countryDetails = values[0];
const userDetails = values[1];
vm.onCountryChange(userDetails.data.country.id);
}).catch(error => console.log(error));
},function(errMsg){
console.log(errMsg)
});
var paramData = {
params : {
id : vm.userData.id
}
};
// gets user data
myService.getUserDetails(paramData)
.then(function (msg) {
vm.user = msg.data.map(function (obj) {
var rObj = {
name: obj.name,
email: obj.email,
country : obj.country.id,
state : obj.state.id
};
return rObj;
})[0];
}, function (errMsg) {
});
}
init();
}
})();
Here onCountryChange()
seems to load earlier even before it gets the user country id, to optimise I can call two services in parallel to fetch data and once the request is completed and user object is set, onCountryChange(countryId) can be triggered to fetch all the states of the country to which user belongs.
Is it beneficial to make two parallel http requests?
How can I ensure that all requests are completed before calling the second function?