Show spinner for multiple calls $ http angularJs

This is a deal.

I want to show spinner when calling $ http, but the problem here is that I have several calls to them, so the examples I found here did not help.

Does anyone have a solution for this?

A way to make calls, so the counter remains until the end of the last call? I hope to express my point of view.

I'm doing it.

angular.module('moduleName', []). factory.("SomeService", function () { return:{ getResources(params) { /* do the $http call */ } } }). controller("SomeCtrl", function (SomeService) { SomeService.getResources(params) }). controller("OtherCtrl", function (SomeService) { SomeService.getResources(params) }); 

Two controllers can simultaneously call a service and may receive different responses.

+1
source share
3 answers

All calls to $http in Angular return a promise.

The $q does not have all the bells and sounds of the Q library on which it is based, but if you look at docs , it has an all method that can be used to provide you with the necessary functionality.

Here you can use it:

 app.controller('HttpController', function($http, $q) { // A hypothetical submit function $scope.submit = function() { // Set a loading variable for use in the view (to show the spinner) $scope.loading = true; var call1 = $http.get(/* ... */); var call2 = $http.get(/* ... */); var call3 = $http.get(/* ... */); $q.all([call1, call2, call3]).then(function(responses) { // responses will be an array of values the individual // promises were resolved to. For this case, we don't // need it, since we only care that they all resolved // successfully. $scope.loading = false; }, function(errorValue) { // If any of the promises is rejected, the error callback // will be resolved with that rejection value, kind of like // an early exit. We want to mark the loading variable // as false here too, and do something with the error. $scope.loading = false; }); }; }); 
+6
source

Use a variable that is initialized by the number of calls you make. Each AJAX callback calls a function that decreases the value of this variable and, if it is zero, deletes the counter.

 num_calls = 3; function considerRemoveSpinner() { if (--window.num_calls == 0) { removeSpinner(); } } $http.get("url").success( function() { /* regular handler */ considerRemoveSpinner(); } ); /* other ajax calls */ 
0
source

You can do this by using an interceptor and passing one flag in the header of each API. What do you need to do. Add one parameter to each $ http call.

Grab it in the interceptor request method using the config.headers property. {{Parameter}}. Based on this flag, a single event is transmitted to display a wait image.

0
source

Source: https://habr.com/ru/post/973978/


All Articles