我想在我的应用程序中编写一个错误处理部分我使用下面的这段代码但是当错误 500 发生时它的工作正常但是有一个小问题或可能是大问题,这就是页面加载第一次和几秒钟错误页面加载后,怎么可能我删除这几秒钟并直接转到错误页面而不加载释放错误的主页?有没有办法在执行其 Controller 后加载 html 模板?
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 500) {
window.location= "http://www.domain.lan/#!/error";
return;
}
if (status == 403) {
// window.location = "dashboard";
return;
}
// otherwise
return $q.reject(responseInterceptors);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
最佳答案
我假设您使用的是 angular ui-router。
第一件事,您需要在 $stateProvider 配置中添加一个状态以通过 ui-router 了解“错误”状态。
路由配置代码
//added state to understand error
$stateProvider.state("error": {
url: "/error",
templateUrl: '/views/error.html',
controller: 'errorCtrl' //optional if you want any specific functionality
});
你做了 window.location 并设置了 url, window.location 导致页面刷新。而不是使用 window.location 使用 window.location.hash
拦截功能变更
var interceptor = ['$rootScope', '$q', '$location', function (scope, $q, $location) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 500) {
//window.location= "http://www.domain.lan/#!/error";
//window.location.hash= "/error"; //it will rewrite the url without refreshing page
$location.path('error');
return;
}
if (status == 403) {
// window.location = "dashboard";
return;
}
// otherwise
return $q.reject(responseInterceptors);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
其他方式你可以尝试相同的 $state.go('error');不要忘记添加 $state 依赖项。
希望这对你有帮助。
让我知道是否还有任何困惑。
关于ajax - ajax请求中的angularjs错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27685654/