I'm trying to getting data from one resource within a controller and with the result, I have to do a second http get request.
$http.get('http://' + ProductionConfig.SERVER + '/api/v1/business-config/').then(function (res) {
$scope.selected= res.data;
console.log($scope.selected);
}, function (err) {
console.error('No se ha podido conseguir los datos de empresa ' + err);
});
$http.get('http://' + ProductionConfig.SERVER + '/api/v1/business/id/' + $scope.selected).then(function (res) {
$scope.business= res.data;
console.log($scope.business);
}, function (err) {
console.error('No se ha podido conseguir los datos de empresa ' + err);
});
But when I'm trying to do the second $http.get, $scope.selected is undefined and it retrieves me an error because it has failed with the query . After that, I have to save the result in an object for using it later.
How can I pose this problem? Thanks.
This is a common scenario when dealing with promises.
You dont know when your first request is done, so, to perform a second one, you have put it inside the first one (when the first one is completed). Something like this:
EDIT : if you need to do something with $scope.business, you have to do it inside the second $http call, again, because angular does not know nothing about when it gonna be resolved. Or you can can create a promise and do something when its resolved. You really need to have a look on how promises works.
I recommend you to have a look to this