m h*_*adi 5 ajax error-handling exception-handling angularjs angularjs-routing
我想在我的应用程序中编写一个错误处理部分我在下面使用这个代码,但是当错误500发生时它的工作正常但是有一个小的或者很大的问题,那就是页面加载起初和几秒钟后错误页面加载,怎么能我删除这几秒钟,直接转到错误页面,而不加载发布错误的主页?有没有办法在执行其控制器后加载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.hash 代替 window.location
拦截功能变更
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 依赖项。
希望这对您有帮助。如果仍有任何困惑,请告诉我。
| 归档时间: | 
 | 
| 查看次数: | 4174 次 | 
| 最近记录: |