从服务返回$ http时拒绝承诺

时间:2015-03-11 14:31:06

标签: angularjs

我知道我可以这样做:

angular.module('app.services').service('Resources', function ($q) {
  this.ProductData = function() {
    var deferred = $q.defer();

    $http.get(url)
        .then(function(result) {
            deferred.resolve(result);
        }, function() {
            defered.reject("error");
        });

    return deferred.promise;
  }
});

但是我可以避免创建延迟obj,但仍然可以同时解决和拒绝吗?

angular.module('app.services').service('Resources', function () {
  this.ProductData = function() {

    return $http.get(url)
        .then(function (result) {
            // how would I do 'deferred.resolve or deferred.reject' here?
        }, function () {
            // how would I do 'deferred.reject' here?
        });
  }
});

1 个答案:

答案 0 :(得分:1)

您应该避免为deferred创建$http和另一个承诺。

如果您需要在实际$http来电成功时拒绝承诺,则需要返回$q.reject()

return $http.get(url)
    .then(function(result){
       if (result.data.length === 0) return $q.reject("error");

       return result;
    }