I make an $http
request when a user clicks a <button>
and I disable/hide/show several elements on screen until the request comes back with either success
or error
Is there a way to know that $http
hasn't had a response yet? The way I am doing it right now is I have a var in my controller called $scope.requesting
which I then use in my HTML page like so:
<img src="img/loader.gif" ng-show="requesting" />
so basically when $scope.requesting
is true, show the spinning ajaxyish loader.
I'd like to ditch the $scope.requesting
if possible and use whatever $http
has to offer, if any at all.
Login Controller
function LoginForm($scope, $http) { $scope.requesting = false; $scope.login = function() { $scope.requesting = true; $http.post('resources/request.php', data, {timeout:20000}) .success(function(data, status, headers, config) { $scope.requesting = false; }) .error(function(data, status, headers, config) { $scope.requesting = false; } ); } }
HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.
$http is an AngularJS service for reading data from remote servers.
get(url) . then(function (response) { console. log('get',response) }) . catch(function (data) { // Handle error here });
You can make use of $http.pendingRequests
array of config objects for currently pending requests. It is possible to use it that way:
$scope.isLoading = function () { return $http.pendingRequests.length !== 0; };
None of the answers here really nailed it for me, and I shun using $http.pendingRequests
, so here's what I've done
My use case was that I had to show a simple "Loading.." message on the top of my viewport if I had any in-flight requests doing things on the server.
Inside .config
, I've registered a new Interceptor. and inside there I've added a simple counter that increments by 1 per request and decrements per response.
$httpProvider.interceptors.push([function () { var pendingRequestsCounter = 0; return { request: function (request) { pendingRequestsCounter++; if (pendingRequestsCounter > 0) { // we have some pending requests, so do something here } return request; }, response: function (response) { pendingRequestsCounter--; if (pendingRequestsCounter === 0) { // we have no pending requests, so do something else here } return response; } }; }]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With