带有额外“成功”方法的$ q装饰器在承诺链中丢失

时间:2017-09-19 11:09:26

标签: angularjs promise decorator extend

我在angularJS中有一个'$ q'的装饰器,它以这种方式添加了一些额外的方法:

  angular
  .module('myApi', [])
  .config(function ($provide) {
    $provide.decorator('$q', function ($delegate) {
      var defer = $delegate.defer;
      $delegate.defer = function () {
        var deferred = defer();
        deferred.promise.success = function (fn) {
          deferred.promise.then(function(response) {
            fn(response.data, response.status, response.headers);
          });
          return deferred.promise;
        };
        return deferred;
      };
      return $delegate;
    });
  });

但是当我在api中执行此操作时,该方法会消失:

var DataFactoryBase =  {

  get: function (url, headers) { 
    var dfr = $q.defer();
    dfr.resolve( api_bridge ({
      execute: function () {
        return $q.resolve($http.get(url, {headers: headers}));
      } 
    }));
    //this line still holds the decorator method
    var withSuccessMethod = dfr.promise;
    //this line returns a promise without the decorator methods
    var lostSuccessMethod = dfr.promise.then(handlerSuccessResponse, handlerErrorResponse);
    return lostSuccessMethod;
  }

}

function handlerSuccessResponse(response) {
  //do stuff
  return $q.resolve(response);
}    


function handlerErrorResponse(response) {
  //do stuff
  return $q.reject(response.data); 
}

如何使 .then 也使用成功方法返回承诺?

1 个答案:

答案 0 :(得分:0)

发现承诺和推迟是两件不同的事情(虽然后者使用前者)。更改调用时返回的promise .then需要在defer中访问底层的promise。可以使用Object.getPrototypeOf()

完成
  angular
  .module('myApi', []).config(function ($provide) {
    $provide.decorator('$q', function ($delegate) {
      var defer = $delegate.defer;
      $delegate.defer = function () {
        var deferred = defer();
        Object.getPrototypeOf(deferred.promise).success = function(callback) { 
          /* code */
        }
        return deferred;
      };
      return $delegate;
    });
  });