Reputation: 1150
In easily understandable pseudo code, I have this in AngluarJS. It is supposed to do a or b or both when we have c. The problem I have now is that the calls are asynchronously called and my data is screwed up.
if(a || c) {
$http.get("path1");
}
if(b || c) {
$http.get("path2");
}
As you see, I can't put the second GET into the .succes method of the first call because of the if statement. I could fiddle around with a function where the second get is listen in, but I think there should be a proper way to do this.
Upvotes: 1
Views: 219
Reputation: 136134
You could just hold of the promise object, that might be returned from the first a || c
check ajax. If that satisfied/unsatisfied $q.when
will resolve the promise by checking the promise
value.
The reason behind using $q.when
is if the promise will undefined then also .then
function of $q.when
going to resolve promise. Example Fiddle
And if promise
will have promise object then it will wait till that promise gets resolved.
Code
var promise;
if(a || c) {
promise = $http.get("path1");
}
$q.when(promise).then(function(response){
if(b || c) {
promise = $http.get("path2");
}
}, function(error){
//error
});
Upvotes: 2
Reputation: 3573
Why does if
statement make a problem?
if(c)
$http.get("path1").success(function(data){
$http.get("path2")
})
else
{
if(a)
$http.get("path1");
else
$http.get("path2");
}
Upvotes: 0
Reputation: 22323
I don't fully see why you have a problem but maybe a separation of concerns will help you to see the full picture.
.factory('yourFactory', function($http){
getFirstThing: function(){
return $http.get("path1");
},
getSecondThing: function(){
return $http.get("path2");
}
});
if(a || c) {
yourFactory.getTheFirstThing;
}
if(b || c) {
yourFactory.getTheSecondThing;
}
Upvotes: 0