Is there a more compact way to return the deferral using an AngularJS function inside a function?

I have this function that I use to call $ http, do some code, and then revert to success or reject a promise.

function getActions() {
    var self = this;
    var defer = this.$q.defer();
    this.$http({
        url: '/api/Action/GetActions',
        method: "GET"
    })
        .success(function (data) {
            // Other code here for success
            self.Actions = data;
            return defer.resolve();
        })
    return defer.promise;
};

      

I would like to simplify this by simply doing something like:

    return this.$http({
        url: '/api/Action/GetActions',
        method: "GET"
    })... etc

      

But if I do this, I may not be able to get any code in success.

Can anyone tell me if there is a way to simplify the code?

+3


source to share


3 answers


function getActions()
{
    var self = this;

    var promise = this.$http({
        url: '/api/Action/GetActions',
        method: "GET"
    });

    promise.success(function (data) {
       // Other code here for success
       self.Actions = data;
    });

    return promise;
}

      



+3


source


you can use

function getActions() {
    return this.$http({
        url: '/api/Action/GetActions',
        method: "GET"
    })... etc
}
getActions().success(function(data){
    self.Actions = data;
    //...do other stuff on success as well
})

      



I personally like your original approach, although it allows multiple then / success / fail blocks (one of which happens after the HTTP request and one additional that you can set in your returned promise). I actually use this approach all the time, although it is a little longer.

0


source


The success

and methods error

added to the promise returned from $http

are not standard then

or catch

chain-of-promise. If you are using then

, you can hook promises as standard:

function getActions() {
  var self = this;
  return this.$http({
    url: '/api/Action/GetActions',
    method: "GET"
  }).then(function(response) {
    // Other code here for success
    self.Actions = response.data;
    return response;
  });
};

      

My advice is to simply ignore the existence of success

and error

and use then

and catch

.

0


source







All Articles