vip*_*dha 17 angularjs angularjs-service angular-promise
如何在Angularjs拦截器中停止请求.
有没有办法做到这一点?
我尝试使用promises并发送拒绝而不是解决!
.factory('connectionInterceptor', ['$q', '$timeout',
function($q, $timeout) {
var connectionInterceptor = {
request: function(config) {
var q = $q.defer();
$timeout(function() {
q.reject();
}, 2000)
return q.promise;
// return config;
}
}
return connectionInterceptor;
}
])
.config(function($httpProvider) {
$httpProvider.interceptors.push('connectionInterceptor');
});
Run Code Online (Sandbox Code Playgroud)
$ http服务有一个选项 超时来完成这项工作.你可以这样做:
angular.module('myApp')
.factory('httpInterceptor', ['$q', '$location',function ($q, $location) {
var canceller = $q.defer();
return {
'request': function(config) {
// promise that should abort the request when resolved.
config.timeout = canceller.promise;
return config;
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (rejection.status === 401) {
canceller.resolve('Unauthorized');
$location.url('/user/signin');
}
if (rejection.status === 403) {
canceller.resolve('Forbidden');
$location.url('/');
}
return $q.reject(rejection);
}
};
}
])
//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);
Run Code Online (Sandbox Code Playgroud)
我最终绕过带有以下角度拦截器的角度XHR调用:
function HttpSessionExpiredInterceptor(sessionService) {
return {
request: function(config) {
if (sessionService.hasExpired()) {
/* Avoid any other XHR call. Trick angular into thinking it's a GET request.
* This way the caching mechanism can kick in and bypass the XHR call.
* We return an empty response because, at this point, we do not care about the
* behaviour of the app. */
if (_.startsWith(config.url, '/your-app-base-path/')) {
config.method = 'GET';
config.cache = {
get: function() {
return null;
}
};
}
}
return config;
}
};
}
Run Code Online (Sandbox Code Playgroud)
这样,任何请求,POST,PUT,...都被转换为GET,以便角度可以使用缓存机制.此时,您可以使用自己的缓存机制,在我的情况下,当会话到期时,我不再关心返回什么.
不确定一般情况下是否可行。但是您可以使用“取消器”启动 $http 请求。
这是这个答案的一个例子:
var canceler = $q.defer();
$http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
// later...
canceler.resolve(); // Aborts the $http request if it isn't finished.
Run Code Online (Sandbox Code Playgroud)
因此,如果您可以控制发起请求的方式,这可能是一个选择。
| 归档时间: |
|
| 查看次数: |
13761 次 |
| 最近记录: |