0

im trying to implement some type of a angularjs directive using TYPESCRIPT that will wrap every $http get request with a boolean parameter "isShow" that will watch the state of the request and update the parameter and show/hide the html element accordingly ( Without the use of $scope or $watch. ) Any idea how to achieve this? Thank you

Basilf
  • 401
  • 5
  • 17

2 Answers2

1

Use the promise disposer pattern:

var spinnerSemaphore = 0;
function own(fn){
    spinnerSemaphore++;
    var res = $q.when(fn());
    fn().then(function(){ spinnerSemaphore--; }, 
            function(){ spinnerSemaphore--; });
    return res; 
}

Which would let you do:

own(function(){
    return $http.get(...); 
});
own(function(){
    return $http.get(...); 
});
own(function(){
    return $http.get(...); 
});
own(function(){
    return $timeout(...); // this also works, and anything else with promises
});

And bind showing the spinner to spinnerSemaphore (so falsey on 0 means hiding the spinner and more than 0 for showing it).

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

If you are looking for a single spinner you can do that quite easily by binding its ng-show (or something equivalent) to $http.pendingRequests.length. Ofcourse this assumed you have $http in scope (or $rootScope).

basarat
  • 261,912
  • 58
  • 460
  • 511