How to execute a function after AngularJS perform all get / post requests?

0

I need to call a function after all get / post requests are complete. Note: I can not call this function multiple times!

        angular
        .module('app.services')
        .config(InterceptorConfig)
        .service('InterceptorService', InterceptorService);

    function InterceptorConfig($httpProvider) {
        $httpProvider.interceptors.push('InterceptorService');
    }

    InterceptorService.$inject = ['$q', '$rootScope', 'Constants'];

    function InterceptorService($q, $rootScope, Constants) {
      return {
        request: function(config) {
            ##########################

            NÃO POSSO CHAMAR AQUI  

            ########################## 
            if (config.method === 'POST' && !config.file) {
                config.headers["Content-Type"] = "application/json";
            }

            if (!config.notloader) {
                $rootScope.$broadcast("loader_show");
            }
            return config || $q.when(config);
        }
    
asked by anonymous 18.02.2016 / 18:07

2 answers

1

You can use the "success" return to execute something on success or even load an error with the "error" return of an http call. Here is the simple example:

$http.get('').success(functional(retorno){
  //Faz algo caso de sucesso
}).error(function(msg){
  //Escreve o erro
});
});
    
30.09.2016 / 18:09
0

You can use events to send a "loading: finished" event, for example, and place a $ scope inside a Controller or Directive "listening / listening" that event and executing when the event occurs.

angular.module('app.services').factory('InterceptorService', ['$q', '$rootScope',
    function ($q, $rootScope) {
        var loadingCount = 0;

        return {
            request: function (config) {
                if (++loadingCount === 1) $rootScope.$broadcast('carregando:andamento');
                return config || $q.when(config);
            },

            response: function (response) {
                if(--loadingCount === 0) $rootScope.$broadcast('carregando:finalizado');
                return response || $q.when(response); 
            },

            responseError: function (response) {
                if(--loadingCount === 0) $rootScope.$broadcast('carregando:erro');
                return $q.reject(response);
            }
        };
     }
 ]).config(['$httpProvider', function ($httpProvider) {
     $httpProvider.interceptors.push('InterceptorService');
}]);

Example using a Directive:

.directive("loader", function ($rootScope) {
    return function ($scope, element, attrs) {
        $scope.$on("carregando:finalizado", function () {
            // chamar uma function aqui - todas requisições get/post foram finalizadas
        });
    };
});

Using a Controller

$scope.$on('carregando:finalizado', function (){
     // chamar uma function aqui - todas requisições get/post foram finalizadas
});
    
18.02.2016 / 18:42