Angular AJAX call chaining

I need to make 2 AJAX calls. The second depends on the first result of the call. Now I do it like this:

Service.getA(car).then(function(carInfo) {
    if (carInfo.success) {
        Service.getB(carInfo.number).then(function(holderInfo) {
            console.log(holderInfo);
        });
    }
});

      

Services:

getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        return carInfo;
    });
},

      

getB

the method is similar - just another URL and other parameters. I am learning angular and want to implement this code with promises and defers (google suggests the code will be prettier). How can i do this?

+3


source to share


2 answers


The way you used to do it is usually you bind the ajax calls, although you can simplify this a bit:

  Service.getA(car).then(function(carInfo) {
     Service.getB(carInfo.number).then(function(holderInfo) {
        console.log(holderInfo);
     });
  });

      

For errors, there is your server return Bad Request 400 and then you can chain the .error () callback instead of defining success based on the success

property.

As Serbrus noted, he $q.all([promise1, promise2])

performs them in parallel, and not one depending on the other.



Your getA method should simply return the promise itself like so:

 getA: function(car) {
    return Server.execute({
       method: 'GET',
       url: 'a/a',
       params: {
           car: car
       },
    });
  }

      

If you really need to chain an additional callback from the service, you can do this:

 getA: function(car) {
    return Server.execute({
        method: 'GET',
        url: 'a/a',
        params: {
            car: car
        },
    }).then(function (carInfo) {
        //do something?

    }, function () {
        //handle error?
    });
},

      

+3


source


As you said, both are similar, apart from url, the parameters I would use with

request : function(url, params) {
    return Server.execute({
        method: 'GET',
        url: url,
        params: params,
    });
},

      



name it

Service.request('a/a', param).then(function(carInfo) {
    if (carInfo.success) {
        Service.request('b/b', carInfo.number).then(function(holderInfo) {
            console.log(holderInfo);
        });
    }
});

      

0


source







All Articles