Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use angularJS interceptor to only intercept specific http requests?

I know how to intercept ALL requests, but I only want to intercept requests from my resources.

Does anyone know how to do this?

services.config(['$httpProvider',function($httpProvider) {     $httpProvider.interceptors.push('myHttpInterceptor'); }]);  services.factory("userPurchased", function ($resource) {     return $resource("/api/user/purchases/:action/:item",          {},          {             'list': {method: 'GET', params: {action: 'list'}, isArray: false},             'save': {method: 'PUT', params: {item: '@item'}},             'remove': {method: 'DELETE', params: {item: '@item'}},         }     ); });  services.factory('myHttpInterceptor', function($q,$rootScope) {     // $rootScope.showSpinner = false;     return {        response: function(response) {         $rootScope.showSpinner = false;         // do something on success         console.log('success');         console.log('status', response.status);         //return response;         return response || $q.when(response);       },       responseError: function(response) {         // do something on error         $rootScope.showSpinner = true;         console.log('failure');         console.log('status', response.status)         //return response;         return $q.reject(response);       }     };   }); 
like image 371
jrutter Avatar asked Apr 11 '14 19:04

jrutter


People also ask

How do you use HTTP interceptors?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.

When implementing an HTTP interceptor which method must be provided?

To implement an interceptor, you'll want to create a class that's injectable and that implements HttpInterceptor. The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent. req is the request object itself and is of type HTTP Request.

What is the use of interceptor in Angularjs?

HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypt and decrypt the request and response information or manipulate the ...

Can I have multiple HTTP interceptors in angular?

So how can I add multiple interceptors? Http doesn't allow to have more than one custom implementation. But as @estus mentioned the Angular team has added a new HttpClient service recently (release 4.3) which supports multiple interceptors concept. You don't need to extend the HttpClient as you do with the old Http .


2 Answers

If you want to intercept only requests from specific resources, you can use optional interceptor property of $request action. Angular's documentation see here (Usage>actions)

JavaScript

angular.module('app', ['ngResource']).   factory('resourceInterceptor', function() {     return {       response: function(response) {         console.log('response intercepted: ', response);       }     }   }).   factory('resourceService', ['$resource', 'resourceInterceptor', function($resource, resourceInterceptor) {     return $resource(":name",          {},          {             'list': {method: 'GET', isArray: false, interceptor: resourceInterceptor}         }     );   }]).   run(['resourceService', '$http', function(resourceService, $http) {     resourceService.list({name: 'list.json'}); // <= intercepted     $http.get('list.json'); // <= not intercepted   }]); 

Plunker: http://plnkr.co/edit/xjJH1rdJyB6vvpDACJOT?p=preview

like image 178
Vadim Avatar answered Oct 04 '22 01:10

Vadim


The only way I know of doing this it to just filter out the requests you want in the response handler.

e.g.

... response: function(response) {     if(response.config.url.startsWith('/api/')) {         //Do your custom processing here     }      return response; } ... 

Polyfill for string.startsWith()

//Taken from http://stackoverflow.com/questions/646628/javascript-startswith if (typeof(String.prototype.startsWith) === 'undefined') {     String.prototype.startsWith = function(str) {         return this.slice(0, str.length) === str;     }; } 
like image 26
rob Avatar answered Oct 04 '22 00:10

rob