有没有一种更紧凑的方法可以在函数中使用AngularJS返回defer



我有一个函数,用来调用$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请求之后,另一个是可选的,您可以在返回的promise中设置)。事实上,我一直在使用这种方法,尽管它有点长。

添加到从$http返回的promise中的successerror方法在promise链接方面的行为与标准thencatch不同。如果您使用then,您可以将承诺作为标准进行连锁:

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

我的建议是忽略successerror的存在,使用thencatch

最新更新