The interceptors of $httpProvider doesn't work for native app?


#1

I want to show loading-mark when each request was started and hide the loading-mark automatically after the request was completed.
There are my code:

  $ionicPlatform.ready(function() {
      $rootScope.$on('loading:show', function() {
         $ionicLoading.show({template: 'Loading...'})
      });
      $rootScope.$on('loading:hide', function() {
        $ionicLoading.hide()
      });
  }
    angular.module('abx.routes', []).config(function($httpProvider) {
      $httpProvider.interceptors.push(['$q', '$location', '$rootScope', function($q, $location, $rootScope) {
      return {
        request: function(config) {
          $rootScope.$broadcast('loading:show');
          config.headers = config.headers || {};
          if (localStorage.access_token) {
            // config.headers.Authorization = 'Bearer ' + $localStorage.token;
            config.headers.access_token = localStorage.access_token;
          }
          return config;
        },
        response: function(response){
          $rootScope.$broadcast('loading:hide');
          return response;
        },
        responseError: function(response) {
          if (response.status === 401 || response.status === 403) {
            alert('no access token error!');
          }
          return $q.reject(response);
        }
      };
    }]);
  })

It’s work for me on the chrome. But doesn’t work on the emulate.
Am I right?


Trying to add $ionicLoading in all $http requests
#2

Hey @Justin_lu,

In my project I started off doing the same thing, but realized that when you have multiple requests firing off to your server, the request and response callbacks are constantly being called, and so your loading:show and loading:hide events are being called often, thus your loader has a constant cycle of

show 
show
hide
hide
show
hide

Also, you may not want to show the loader on every request because then your user would constantly be having the loader flash in their face, which isn’t a great user experience. The solution I came up with would be something like this:

$rootScope.$broadcast('loading:show');

User.get().then(function(user){
	$scope.user = user;
}).finally(function(){
	$rootScope.$broadcast('loading:hide');
});

That way you show your loader only on requests you desire, perhaps on ones that take a while. In my project I show the loader after a 400ms delay which you can specify with

$ionicLoading.show({ template: 'Loading...', delay: 400 });

Hope this helps!


#3

Thank a lot. It’s awesome.