declaring a promise in angularJS with named success/error callbacks

前端 未结 3 1472
执念已碎
执念已碎 2021-02-02 13:56

I am trying to do something very similar to the $http service. From my understanding $http return a promise object.

When using it the syntax is :

$http(.         


        
3条回答
  •  故里飘歌
    2021-02-02 14:51

    You don't need change source code. Angular provide a way to change any service in angular include $q.

    $provide.decorator is perfect for your requirement here is my code.

    put it at app.module('...').config

    $provide.decorator('$q', function($delegate) {
      function httpResponseWrapper(fn) {
        return function(res) {
          if (res.hasOwnProperty('data') && res.hasOwnProperty('status') && res.hasOwnProperty('headers') && res.hasOwnProperty('config') && res.hasOwnProperty('statusText')) {
            return fn(res.data, res.status, res.headers, res.config, res.statusText);
          } else {
            return fn(res);
          }
        };
      };
      function decorator(promise) {
        promise.success = function(fn) {
          return decorator(promise.then(httpResponseWrapper(fn)));
        };
        promise.error = function(fn) {
          return decorator(promise.then(null, httpResponseWrapper(fn)));
        };
        return promise;
      };
      var defer = $delegate.defer;
      $delegate.defer = function() {
        var deferred = defer();
        decorator(deferred.promise);
        return deferred;
      };
      return $delegate;
    });
    

提交回复
热议问题