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); } }; });
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.
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.
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 ...
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 .
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
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; }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With