angualrjs 配置超时时间
timeout 1
本想通过$httpProvider的defaults属性配置timeout时间, defaults中没有这个属性. https://docs.angularjs.org/api/ng/provider/$httpProvider#defaults
timeout 2
在拦截器中为request的config配置timeout, 在response中根据xhrStatus=timeout来处理超时. 奈何response中没找到这个xhrStatus ![](https://images2018.cnblogs.com/blog/213419/201804/213419-20180401112302128-243653749.png)
官网里说status=-1表示请求被取消, timeout时就会取消请求, 那就用这个来判断吧
https://docs.angularjs.org/api/ng/service/$http#$http-returns
代码
``` (function() {
angular.module("mobile")
.factory('HttpInterceptor', ['$q',
function($q) {
return {
request: function(config) {
// 设置超时时间, 毫秒
config.timeout = 1;
if (config.url.search("service/") < 0)
return config;
if (localStorage.getItem('token')) {
config.params = config.params || {};
config.params['token'] = localStorage.getItem('token');
config.params['t'] = new Date().getTime();
}
return config;
},
requestError: function(err) {
return $q.reject(err);
},
response: function(res) {
console.log('res: ',res);
if(res.statusText=='timeout')
{
console.log('timeout: ',111);
}
if (res.data && res.data.code) {
switch (res.data.code) {
case '000':
return res
case '100':
// alert(res.data.msg)
// 账号未注册
localStorage.removeItem('token');
localStorage.removeItem('groupid');
return res
case '200':
// session 无效
console.log(res.data.msg)
localStorage.removeItem('token');
localStorage.removeItem('groupid');
window.location.href = '';
break
}
}
return res
},
responseError: function(err) {
if (-1 === err.status) {
// 请求超时
alert('请求超时');
} else if (500 === err.status) {
// 处理各类自定义错误
} else if (501 === err.status) {
// ...
}
return $q.reject(err);
}
};
}
])
.config(['$httpProvider',
function($httpProvider) {
$httpProvider.interceptors.push('HttpInterceptor');
}
])
})();