【发布时间】:2016-11-30 07:42:41
【问题描述】:
我在我的 AngularJS 应用程序中添加了一个 HttpRequestInterceptor,以便在每次请求失败时显示一个 toastr。
angular.module('spwApp.factories')
.factory('httpRequestInterceptor', ['$q', '$injector', '$cookies', '$rootScope', function($q, $injector, $cookies, $rootScope) {
return {
'request': function($config) {
var token = $cookies.get('token');
$config.headers['Authorization'] = 'Bearer ' + token;
return $config;
},
'responseError': function(rejection) {
var toastr = $injector.get('toastr');
var $state = $injector.get('$state');
toastr.options = {
"closeButton" : true,
"preventDuplicates" : true,
"timeOut": "50000",
"extendedTimeOut" : "50000"
};
toastr.remove();
switch (rejection.status) {
case 401:
if ($state.current.name != 'login') {
$state.go('login');
toastr.info('Re-enter username/password', 'Invalid sessions', toastr.options);
}
break;
case 403:
toastr.error('You do not have the rights', 'Forbidden', toastr.options)
$state.go('home');
break;
case 404:
toastr.error('Cannot found', '??', toastr.options);
$state.go('home');
break;
case 500:
toastr.error('Unexpected error', 'Hum...', toastr.options);
$state.go('home');
break;
case -1:
toastr.error('Connection to server not possible', 'Ouch...', toastr.options);
$state.go('home');
break;
default:
toastr.error('That is not supposed to land here', 'Oops...', toastr.options);
$state.go('home');
break;
}
return $q.reject(rejection);
}
};
}]);
在某些页面上,我必须从我的服务器解析多个数据
.state('stateA', {
url: '/urlToStateA',
views: {
'content@stateA': {
templateUrl: 'app/stateA.html',
controller: 'controllerA',
controllerAs: 'vm',
resolve: {
dataA: ['myService', function(myService) {
return myService.getDataA();
}],
dataB: ['myService', function(myService) {
return myService.getDataB();
}],
dataC: ['myService', function(myService) {
return myService.getDataC();
}]
}
}
}
})
因此当我的服务器关闭时,每个请求都会得到一个rejection.status == -1,然后显示toastr Connection to server not possible
问题是toastr.remove(); 行不起作用。它应该删除所有的 toastr 但什么都不做。
如何在添加新的 toastr 之前删除它?我可以用一些纯 JavaScript 替换不工作的 toastr.remove() 来手动选择和删除 toastr 吗?
【问题讨论】:
标签: angularjs angular-http-interceptors angular-toastr