Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

In my service:

        var deferred = $q.defer();         var promise = deferred.promise;          deferred.resolve('success');         deferred.reject('error');          /* Handle success and error */         promise.success = function(fn) {              promise.then(function(response) {                  fn(response);              });              return promise;         };          promise.error = function(fn) {              promise.then(null, function(response) {                  fn(response);              });              return promise;         }; 

In my controller:

        promiseService.myPromise()             .success(function(data){                  $scope.success= data;              })             .error(function(data){                  $scope.error = data;              }); 

I juste Handle the Success and Error from the promise ($q service). I need this code in a lot of other service so I would to extend directly the $q service with a custom.

So I would like something like this in my service:

    var deferred = myPromiseService.$qCustom.defer();     var promise = deferred.promise;      deferred.resolve('success');     deferred.reject('error');      return promise; 

Any idea? I found some explanation to extend filter in Angularjs my problem is to find the good way to extend all the functionality of the $q and add my custom.

I start with something like that, it's work to handle the $q out of the box :

angular.module('myApp').service('myPromiseService', function($q){    $qCustom = $q;    }); 
like image 829
Matohawk Avatar asked May 28 '13 16:05

Matohawk


People also ask

What is $q in AngularJS?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.

What is Q defer () in AngularJS?

Simply put you can use $q. defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.

What is defer in promise?

The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.

What is then function in AngularJS?

then() function to handle the callbacks. Traditional promises (using the $q Service in Angular) have a . then() function to provide a continuation on success or failure, and . then() receives parameters for a success and failure callback.


2 Answers

Here's a full solution picking up where @jessegavin left off.

var myApp = angular.module("myApp", []);  myApp.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;       };       deferred.promise.error = function (fn) {         deferred.promise.then(null, function(response) {           fn(response.data, response.status, response.headers);         });         return deferred.promise;       };       return deferred;     };     return $delegate;   });  }); 
like image 61
Joshua Kifer Avatar answered Oct 02 '22 04:10

Joshua Kifer


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.

like image 30
jessegavin Avatar answered Oct 02 '22 05:10

jessegavin