有没有更简洁的方法在函数中使用AngularJS返回延迟?

有没有更简洁的方法在函数中使用AngularJS返回延迟?,angularjs,Angularjs,我使用这个函数调用$http,执行一些代码,然后返回成功或拒绝承诺 function getActions() { var self = this; var defer = this.$q.defer(); this.$http({ url: '/api/Action/GetActions', method: "GET" }) .success(function (data) { // Oth

我使用这个函数调用$http,执行一些代码,然后返回成功或拒绝承诺

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;
};
我想通过以下操作来简化此过程:

    return this.$http({
        url: '/api/Action/GetActions',
        method: "GET"
    })... etc
但是如果我这样做,那么我将无法在成功中获得任何代码

有人能告诉我有没有什么方法可以简化代码吗?

您可以使用

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;
}
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
})

我个人更喜欢您最初的方法,因为它允许多个then/success/fail块(一个发生在http请求之后,另一个可选,您可以在返回的承诺中设置)。实际上,我一直在使用这种方法,尽管它有点长。

添加到从
$http
返回的承诺中的
成功
错误
方法在承诺链接方面与标准的
然后
捕获
不一样。如果使用
,则可以将承诺作为标准链接:

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;
  });
};
我的建议是忽略
success
error
的存在,然后使用
then
catch