menu

How to use http interceptor to handle http request and response in ionic

  • date_range 11/07/2015 00:00 info
    sort label

The $http service is a core Angular service that facilitates communication with the remote HTTP servers.
In general we use it in our controller or service as follow :-

 // Simple GET request example :
 $http.get('/someUrl').
  success(function(data, status, headers, config) {
   // this callback will be called asynchronously
   // when the response is available
  }).
  error(function(data, status, headers, config) {
   // called asynchronously if an error occurs
   // or server returns response with an error status.
  });

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

To use $httpProvider write the following code inside app.js as follow.

Inject $httpProvider provider inside .config :-

 .config(function ( $httpProvider){
 }

Inside this .config function add the following code :-


   $httpProvider.interceptors.push(function($rootScope) {
     return {
       request: function(config) {
         return config
       },
       requestError: function(data, status, headers, config) {
         alert('Something went wrong.')
       },
       response: function(response) {
         return response
       },
       responseError:function(data, status, headers, config) {
         switch (status) {
           case 401:
             alert(data.message)
             break;
           case 500:
             alert('Internal Server Error')
             break;
           default:
             alert('Something went wrong.')
         }
         return data
       }
     }
   })