ajax - ajax请求中的angularjs错误处理

标签 ajax angularjs error-handling exception-handling angularjs-routing

我想在我的应用程序中编写一个错误处理部分我使用下面的这段代码但是当错误 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/

相关文章:

javascript - jquery ajax 调用后重新加载页面

javascript - 单击 "Buy Now"按钮时,ajax post 应将数据发送到路由 "/buy"

html - CSS:底部居中引导分页元素

javascript - FixedDataTable组件的“You must set either a height or a maxHeight”错误

php - 如果 Joomla 中发生任何错误,则发送一个事件

python - 训练自己的数据集。 Mask_RCNN资源耗尽: OOM when allocating

javascript - 使用ajax更新一个div

jquery - 如何从服务器端停止重定向

javascript - 如何使用 angularjs 获取用户所属的安全组列表

c# - Breeze - 如何在保存更改调用之前处理同一 View 中两个实体的状态