如果需要登录,Angularjs$http拦截器会暂停异步请求
Angularjs $http interceptor pause async requests if login required
我的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);
}
}
});
问题是,如果多个请求异步触发,则会显示每个请求的登录名。
如何在用户登录之前停止执行所有其他请求?目前,当发出一个请求时,这种方法就可以工作。我不想取消所有其他请求,我希望在用户登录后解决这些请求。
您可以在返回的第一个未授权请求上设置一个标志,并拒绝以下所有未授权请求/响应:
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);
}
}
});
相关文章:
- ajax请求的顺序总是不同的
- Meteor如何接收HTTP请求
- 有没有一种方法可以防止img get请求使用css或js发生
- 从ajax请求中获取javascript对象
- JSONP请求返回结果,但也触发error_callback
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 如何临时暂停浏览器渲染,然后恢复整个页面
- jQuery循环在特定位置暂停
- Ajax请求文档就绪会导致jquery加载缓慢
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- 在openshift node js应用程序中获取请求
- 反应路由器弄乱了请求网址
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 暂停函数执行流程,直到ajax请求完成
- 如果需要登录,Angularjs$http拦截器会暂停异步请求
- 是否可以间隔暂停视频,并请求验证码以继续播放
- 如何使用请求动画帧暂停和重新启动秒表计时器
- 暂停http请求,直到缓存准备就绪而不进行轮询
- 重复Jquery .ajax一定次数,并暂停,直到请求完成