0

I have to make two $http call but the second call must be based on first response(only if there is any error).

  • 1
    Nest the second call in the response callback of first. – Tushar Oct 06 '16 at 03:40
  • See [Multiple Sequential Async JavaScript Functions](http://stackoverflow.com/questions/27642958/multiple-sequential-async-javascript-functions), [sequential calls of methods asynchronously](http://stackoverflow.com/questions/9433725/sequential-calls-of-methods-asynchronously) – Tushar Oct 06 '16 at 03:42

2 Answers2

0

The best option is to use .then() with your request. When using .then, you can pass in multiple functions that will be called - the first if it is successful, the second if there is an error. So, it would look like this:

//First http call
$http.get('http://your-url.com')
  .then(function (trsponse) {
    //Call was successful; do something
  }, function (response) {
    //Call was unsuccessful; Grab whatever you need from the response and make your second http call:
    var data = response.data;
    var statusCode = response.status;
    var statusText = response.statusText;
    $http.get('http://your-second-url.com');  
  });

The response that gets passed into your functions will have these properties on it:

 data – The response body
 status – The status code of the response (e.g. 404)
 headers – Headers on the response
 statusText – The text of the status of the response
Joseph
  • 865
  • 5
  • 20
  • @Phil Done :p thank you! First answer on here, not a great start ;) – Joseph Oct 06 '16 at 04:09
  • 1
    It's now a good answer, just wish the initial downvoter would see that you've improved it. In fact, this is the only answer so far to notice that OP said they want to do the second HTTP request in case of an error. – Phil Oct 06 '16 at 04:11
0

You can do something like this:

var promise1 = $http.get('firstUrl.com');

promise.then(
  function(payload) {
    $scope.movieContent = payload.data;
  })
  .catch(function (error) {
    secondUrl();
    console.log("Something went terribly wrong.");
  });

Then :

var secondUrl = function(){

   var promise2 = $http.get('secondUrl.com');

   promise2.then(
   // get the data and also other required functions
  );

}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108