javascript - 访问 header 数据并处理 Angular http 请求中的错误代码

标签 javascript angularjs http

这就是我在 Angular 中处理路由的方式。我有几个文件,其中存储了每条路线所需的所有数据,我会像这样遍历这些数据。 .html 请求用于加载模板,.action 用于 AJAX 请求。

我需要做的是处理服务器不成功的所有情况(300、400、500 等)。我用谷歌搜索了所有我认为相关的信息,找到了一些关于它的信息,但似乎没有什么相关或不够清楚。我究竟如何访问请求的 header 数据?

Application.config(['$routeProvider', '$interpolateProvider', '$httpProvider',

    function($routeProvider, $interpolateProvider, $httpProvider) 
    {

        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');

        for (var i=0; i < applicationRoutes.length; i++) {

            if (applicationRoutes[i].hasInitialData)
            {
                $routeProvider.when('/' + applicationRoutes[i].path + '.html', {

                    templateUrl: applicationRoutes[i].path + '.html',
                    controller: applicationRoutes[i].controller + ' as ' + applicationRoutes[i].controllerAlias,
                    resolve: {
                        initData : ['Initialize', '$route', function(Initialize, $route)
                        {
                            //console.log($route.current.$$route);
                            return Initialize.serverData('/' + $route.current.$$route.pathBase);
                        }]
                    },
                    pathBase: applicationRoutes[i].path

                }).otherwise('/404');
            }
            else
            {
                $routeProvider.when('/' + applicationRoutes[i].path + '.html', {

                    templateUrl: applicationRoutes[i].path + '.html',
                    controller: applicationRoutes[i].controller + ' as ' + applicationRoutes[i].controllerAlias,
                    pathBase: applicationRoutes[i].path

                }).otherwise('/404');

            }

        }

        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

    }

]);

最佳答案

我看不到你的服务器调用,但假设你已经汇总了一个服务来调用带有 $http 的端点,请记住你可以使用失败处理程序作为 promise 的第二个参数,所以

$http(req).then(function(){...}, function(){...});

意味着你可以做到这一点

    $http(req).then(function(someData){/*This is the success*/},function(reason){/*the reason holds the reason it faild, reason.data etc */});

关于javascript - 访问 header 数据并处理 Angular http 请求中的错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32520990/

相关文章:

javascript - 如何将数组发布到我的 firebase 数据库中?

html - 确定哪个自定义 HTML 标记冒犯了 IE8

javascript - <td ng-repeat ="x in names |orderBy:' -印地语' | limitTo :1"> {{x. name}} 如果用户编辑任何单个数据槽,则标记应更新

php - 当我用 PHP 创建 PDF 时,如何让浏览器正确呈现它?

python - 生成 PDF 文件的 Web 服务器

java - HttpsURLConnection 中的什么方法调用实际发送了 HTTP 请求?

javascript - node-webkit 右键单击​​链接并在默认浏览器中打开

javascript - gulp 和 babel 以及 gulp-live-server

javascript - 显示多个API调用的结果

javascript - 如何在使用网页时保持 Foundation Off-Canvas 打开