I recently started working with angular JS and I encountered a problem while trying to implement $http within the response of another $http call.
My problem is that when I make a $http call within the response of another $http call, the data is not displayed on the view. The view gets rendered before the second $http call is made. I tried using promises but without success. Below is the code snippet from another answer that I used with a few modifications.
angular.module('App', [])
.controller('Ctrl', function($scope, resultsFactory) {
resultsFactory.all().then(
function(res){
$scope.results = res;
},
function(err){
console.error(err);
}
);
})
.factory('resultsFactory', function($http, $timeout, $q) {
var results = {};
function _all(){
var d = $q.defer();
$http({
url: url,
method: 'POST'
}).then(function (response) {
var f = {};
f.id = response.data.id;
f.name = response.data.name;
$http({
url: url,
data: "id="+response.data.parent_id,
method: 'POST'
}).then(function (response1) {
f.parentname = response1.name;
d.resolve(f);
});
});
return d.promise;
}
results.all = _all;
return results;
});
The id and name are displayed correctly on the view, but the parent name is not showing anything. I have debugged it and found that it is undefined when the view is rendered. It sets the value for parentname after the rendering. Can anyone help me resolve this issue?