加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax请求中的angularjs错误处理

发布时间:2020-12-15 22:51:17 所属栏目:百科 来源:网络整理
导读:我想在我的应用程序中编写一个错误处理部分我在下面使用这个代码,但是当错误500发生时它的工作正常但是有一个小的或者很大的问题,那就是页面加载起初和几秒钟后错误页面加载,怎么能我删除这几秒钟,直接转到错误页面,而不加载发布错误的主页?有没有办法在执
我想在我的应用程序中编写一个错误处理部分我在下面使用这个代码,但是当错误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);

解决方法

我假设你使用的是角度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','$location',$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(‘错误’);不要忘记添加$state dependancy.

希望这对你有所帮助.如果仍有任何混淆,请告诉我.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读