cgross / angular-busy

Show busy/loading indicators on any element during $http requests (or any promise).
http://cgross.github.io/angular-busy/demo
MIT License
1.44k stars 256 forks source link

Named promises and a factory #30

Closed pocesar closed 9 years ago

pocesar commented 10 years ago

Since the deprecation of automatic promise unwrapping in 1.2+, it would be nice to be able to name a promise, that you could get a factory from adding it, and you create a new promise everytime you want, but keep track of only one instance.

Use case:

Every time you press a button, you'll execute the same promise. Since promises can only be either resolved, pending or rejected, you can have only one instance. So, in your module.run, you add a couple of named promises that you expect to use thorough your app:

angular.module('myapp', ['cgBusy'])
.run(['_cgBusyTrackerFactory', '$q', function(_cgBusyTrackerFactory, $q){
  _cgBusyTrackerFactory.add('myPromise', function promiseFactory(originalPromise){
     if (!originalPromise) {
        originalPromise = $q.defer();
     } 
     originalPromise.promise.then(function(){
       // do something before returning it
     });
     return originalPromise;
  });
}])
.controller('myCtrl', function(_cgBusyTrackerFactory, $scope, SomeHttpService){
   $scope.stuff = function(){
     _cgBusyTrackerFactory.get('myPromise')(SomeHttpService.fetch());
   });
});
<div cg-busy="{promise:'myPromise'}" ng-click="stuff()"></div>

so you can reuse the same factory and pattern and keep it consistent application-wide.

cgross commented 10 years ago

I'm not really following. Angular-busy will work if you just update the the reference location on scope. In other words, if you have a promise on $scope called myPromise, you can keep setting that promise in your button click handler. You can set cg-busy="myPromise" and thats it. Anytime a new promise is set into $scope.myPromise, cg-busy will activate.

pocesar commented 10 years ago

it's a singleton promise, like, disable 4 buttons at once plus 2 panels, scattered through many controllers and directives, but using one central promise, but don't rely on a controller/scope member, but rather from the singleton instance from the service.

kodeine commented 10 years ago

i have $http as a service, i call

$scope.refresh = function () { Service.get(1) .success(function (response) { $scope.list = response.data; }); }

--> does not work. any idea?