title: Infinite loop in interceptor
body: <p>I've made an AngularJS website working with an API. This API provides few features like authentication (Oauth).</p>
  
  <p>When the API returns a 401 error, it means that the <code>access_token</code> has expired and it needs to be refreshed with the <code>refresh_token</code>.</p>
  
  <p>I created an interceptor in AngularJS. Its goal is to check if the result returned by the API is a 401 error and if it's the case, it must refresh the token and then, process the previous rejected request.</p>
  
  <p>The problem is that the interceptor creates an infinite loop. After the second failure of the initial request, it should stop but it doesn't.</p>
  
  <pre class="lang-js prettyprint-override"><code>angular.module('myApp')
  .factory('authInterceptor', function ($rootScope, $q, $window, $injector) {
  
    return {
  
      // If the API returns an error
      'responseError' : function(rejection) {
  
        // If it's a 401
        if (rejection.status == 401) {
  
          var deferred = $q.defer();
  
          $injector.get('$http').post('http://my-api.local/api/oauth/token', {
            grant_type    : 'refresh_token',
            client_id     : 'id',
            client_secret : 'secret',
            refresh_token : $window.sessionStorage.refresh_token
          }, {
            headers : {
              'Content-Type'  : 'application/x-www-form-urlencoded'
            },
            transformRequest  : function(obj) {
              var str = [];
              for(var p in obj)
              str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
              return str.join("&amp;");
            }
          })
          // New token request successfull
          .success(function(refreshResponse) {
  
            // Processing the failed request again (should fail again because I didn't saved the new tokens)
            $injector.get('$http')(rejection.config).success(function(data) {
  
              deferred.resolve(data);
  
            })
            .error(function(error, status) {
  
              deferred.reject();
  
            });
  
            return deferred.promise();
  
          })
          // New token request failure
          .error(function(error, status) {
  
            deferred.reject();
            // $location.path('users/login');
  
            return;
  
          });
  
        }
        // If it's another errorenter code here
        else
          return rejection;
  
      }
  
    }
  
  });
  </code></pre>
  
  <p>So this code:</p>
  
  <ul>
  <li>Starts when the first request fails</li>
  <li>Refreshes the token</li>
  <li>Retries the request but fails again (&lt;- I just want to make it stop here)</li>
  <li>Refreshes the token</li>
  <li>Retries the request but fails again</li>
  <li>Refreshes the token</li>
  <li>Retries the request but fails again</li>
  <li>etc...</li>
  </ul>