2016-04-27 38 views
0

我在我的angularjs应用程序中有一个$http

如果我的api返回未经授权的回复,我会显示登录信息。

一旦用户通过模态登录,请求拦截器就会重试$http请求。

app.factory('LoginInterceptor', function ($injector, $timeout, $q) { 
    return { 
     request: function (config) { 
      return config; 
     }, 
     response: function (response) { 
      var LoginModalService = $injector.get('LoginModalService'), 
       $http = $injector.get('$http'), 
       $location = $injector.get('$location'), 
       $rootScope = $injector.get('$rootScope'), 
       url = response.config.url.split('?')[0]; 

      if (response.data && response.data.token_status <= 0) { 

       return $timeout(angular.noop, 1000).then(function() { 
        return LoginModalService.show(); 
       }).then(function() { 


        return $http(response.config); 
       }, function() { 
        $location.path('/login'); 

        return $q.reject(response); 
       }); 
      } 

      return response || $q.when(response); 
     } 
    } 
}); 

问题是,如果多个请求异步触发登录显示每个请求。

如何停止执行所有其他请求直到用户登录?目前,只有一个请求发生时才能使用。我不想取消所有其他请求,我希望他们一劳永逸地解决用户在签署

+0

你是什么意思的“暂停”?您想要在显示模式时取消所有并行请求,还是希望在用户登录后执行它们? –

+0

用户登录后执行它们。 - 请参阅编辑问题 – CharliePrynn

+0

我写了一个工厂,以便更好地控制。有一个[看](https://www.npmjs.com/package/angular-httpshooter) – Siddharth

回答

0

,你可以设置一个标志第一未经授权的请求返回,并拒绝所有未授权之后请求/响应:

app.factory('LoginInterceptor', function ($injector, $timeout, $q) { 

    var isAuthorized = true; 

    return { 
     request: function (config) { 
      if(isAuthorized){ 
       return config 
      }else{ 
       return $q.reject(config); 
      } 
     }, 
     response: function (response) { 
      var LoginModalService = $injector.get('LoginModalService'), 
       $http = $injector.get('$http'), 
       $location = $injector.get('$location'), 
       $rootScope = $injector.get('$rootScope'), 
       url = response.config.url.split('?')[0]; 

      if (response.data && response.data.token_status <= 0) { 

       if(isAuthorized){ 

        isAuthorized = false; 

        return $timeout(angular.noop, 1000).then(function() { 
         return LoginModalService.show(); 
        }).then(
         return $http(response.config); 
        }, function() { 
         $location.path('/login'); 

         return $q.reject(response); 
        }); 
       }else{ 
        return $q.reject(response) 
       } 

      } 

      return response || $q.when(response); 
     } 
    } 
}); 
+0

我不希望这些请求被拒绝,我希望他们在用户登录后解决。 – CharliePrynn

+0

然后你需要存储这些请求/响应的承诺,比如说在用户登录后将它们放入一个数组中,解决该数组中的所有承诺 – MarkoCen