How can I extend $q promise in Angularjs with a .success and .error

后端 未结 3 1595
有刺的猬
有刺的猬 2020-12-28 15:37

I wrote this little code in a custom service in AngularJS.

In my service:

        var deferred = $q.defer();
        var promise = deferred.promise;         


        
3条回答
  •  Happy的楠姐
    2020-12-28 16:15

    If you want to change the default behavior of something that is injected by angular, you can use the decorator() method on the $provide service.

    var myApp = angular.module("myApp", []);
    
    myApp.config(function ($provide) {
      $provide.decorator("$q", function($delegate) {
        // The $delegate argument here refers to the $q service.
    
        $delegate.defer = function() {
          alert("You just tried to call defer()!");
        };
    
        // Now, every time angular provides an instance of $q via
        // injection, it will return your customized version of $q.
    
        return $delegate;
      });
    });
    

    See the example above in action at http://plnkr.co/edit/RuZF2cGkVHwlu7NIhxEZ?p=preview

    As to modifying $q to add the success and error functions, I am not sure at the moment. But I am pretty sure that this is where you'd want to do it.

提交回复
热议问题