14923

Circular dependency while pushing http interceptor

I am using http Interceptor to intercept each http request in my application. But I am getting <strong>Circular dependency found: $http <- APIInterceptor <- $http <- $templateRequest <- $compile</strong>

here is my Service code:

mPosServices.factory('mosServiceFactory', function ($http, $rootScope, $cookies, $q) { return{ refresh_token: function () { var refreshToken = $http({ method: "get", url: "myservice/oauth/token?grant_type=refresh_token&client_id=restapp&client_secret=restapp&refresh_token=" + $cookies.get('refresh_token'), }) return refreshToken; } }); mPosServices.service('APIInterceptor', ['mosServiceFactory','$cookies',function (mosServiceFactory,$cookies) { var service = this; service.request = function (config) { if (!$cookies.get('access_token')) { //if access_token cookie does not exist mosServiceFactory.refresh_token().then(function (response) { var date = new Date(); date.setTime(date.getTime() + (response.data.expiresIn * 1000)); $cookies.remove('access_token'); $cookies.put('access_token', response.data.value, {expires: date}); $cookies.put('refresh_token', response.data.refreshToken.value); }); //call the refresh_token function first } return config; }; service.responseError = function (response) { return response; }; }]);

and pushing it as:

$httpProvider.interceptors.push('APIInterceptor');

in config function. Am I doing something wrong here? Even I tried to inject $http manually using

$injector

, but getting same error. Kindly Help me.

Answer1:

You indeed need to add use $injector to get mosServiceFactory instance inside of interceptor. But this is not all you need to do. You also need to make sure you don't fall into infinite request loop because interceptor also makes a request. What you can do is to check if current request is the one for token refresh and if so don't fire one more request, I'm checking the URL for this.

One more important thing to mention. You need to return promise object from interceptor which resolves to original request config. This way it guaranties that intercepted request will be reissued after token is retrieved.

All together will look like this:

mPosServices.service('APIInterceptor', ['$injector', '$cookies', function($injector, $cookies) { var service = this; service.request = function(config) { if (!$cookies.get('access_token') && config.url.indexOf('myservice/oauth/token?grant_type=') === -1) { return $injector.get('mosServiceFactory').refresh_token().then(function(response) { var date = new Date(); date.setTime(date.getTime() + (response.data.expiresIn * 1000)); $cookies.remove('access_token'); $cookies.put('access_token', response.data.value, { expires: date }); $cookies.put('refresh_token', response.data.refreshToken.value); }).then(function() { return config; // <-- token is refreshed, reissue original request }); } return config; }; service.responseError = function(response) { return response; }; }]);

Check the demo I was testing solution on to see how it recovers original request after token is loaded.

<strong>Demo:</strong> http://plnkr.co/edit/1Aey2PThZQ4Y8IRZuVOl?p=preview

Recommend

  • Facebook SDK .NET - (#200) The user hasn't authorized the application to perform this action
  • PHP Instagram API - How to get MIN_TAG_ID and MAX_TAG_ID
  • Laravel 5.3 : Passport Implementation - {“error”:“invalid_client”,“message”:“Client authentication f
  • After first scuccessful login & logout windows live sign in button is not working on windows pho
  • How do I do two has_many/belongs_to relationships between two models?
  • TypeError upon authenticating user using Google OAuth 2
  • connecting to web api using c#
  • Spring integration warning Referenced bean 'org.springframework.scheduling.support.PeriodicTrig
  • Google Contacts API asp.net settings and authorization token
  • Unable to save a query as a view table
  • android-NestDK stuck with pincode
  • Return list of all users in BOX Enterprise Account
  • OAuth2 flow for mobile app
  • how to avoid the dependencies hell with unit test in angular 2+
  • Basic Authentication over redirection
  • Failed to create any app request
  • Instanciate service on startup in Angular2
  • Uber API - requests endpoint cannot read read json
  • How to Save JSON data to SQL server database in C#?
  • Salesforce Different WSDL files and when to use
  • How can I speed up CURL tasks?
  • Specifying Castle WCF Integration Facility Endpoint Behavior per Endpoint
  • Do I need to reset a Perl hash index?
  • Display images in Django
  • How to render a blob on a canvas element?
  • Seeking advice on Jetty HttpClient Hang
  • Why is an OPTIONS request sent to the server?
  • Spring security and special characters
  • Is there a amazon webstore API for customers?
  • How to get a value (ex: baseURL) in every Karate feature?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Invalid access key error using credentials redeemed from an amazon open id token
  • Circular dependency while pushing http interceptor
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • AngularJs get employee from factory
  • How to set the response of a form post action to a iframe source?
  • Angular 2 constructor injection vs direct access
  • Change div Background jquery
  • File not found error Google Drive API
  • UserPrincipal.Current returns apppool on IIS