Angular Catch 方法不适用于 $http get 请求 [英] Angular Catch method not working with $http get request

查看:34
本文介绍了Angular Catch 方法不适用于 $http get 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在处理来自 API 的错误的同时,巧妙地管理来自控制器的服务函数调用.

I am trying to neatly manage service function calls from the controller while handling errors from the API.

但是,当我执行以下操作时,即使 API 返回 403 或 404,我仍然在控制台中看到 即使有 403 和 404 错误也显示此内容.

However when I do the following, I still get this is showing even with 403 and 404 errors in my console even when the API throws back a 403 or 404.

我假设如果我在我的服务文件中添加了 catch 这可以工作,但我更喜欢从控制器管理它.这可能吗?

I am assuming this could work if I added catchin my services file but I would prefer keep this managed from the controller. Is this possible?

控制器:

angular.module('EnterDataCtrl', []).controller('EnterDataController', ['$scope', 'Data', '$state', function ($scope, Data, $state) {
    vm = this;
    vm.getRules = function (e, rule_query, data) {
        if (e.keyCode == 13) {

            Data.getRules(rule_query,data).then(function (data) {
                console.log('this is showing even with 403 and 404 errors');
            }).catch(function(res) {
                console.log(res);
            });
        }
    }
}]);

服务:

angular.module('EnterDataService', []).factory('Data', ['$http', function ($http) {

    return {

        getRules: function getRules(rule_query,data) {
            var apiBase = apiUrl + 'get-rules';
            var config = {
                handleError:true,
                params: {
                    rule_query: rule_query,
                    data : data
                }
            };
            return $http.get(apiBase, config).catch(function () {});
        }

    }
}]);

推荐答案

在您的服务中,您无需执行任何操作即可设置捕获.这通常是不好的做法,如果您要使用 catch 块,则在那里处理错误.如果没有,根本不要声明捕获.

In your service, you are setting up the catch without doing anything. This in general is bad practice, if you're going to use a catch block, then handle the error there. If not, don't declare the catch at all.

您可以从服务方法中完全删除捕获,这将导致控制器的捕获处理它.

You can either remove the catch completely from the service method, which should result in your controller's catch handling it.

或者,您可以将捕获留在服务调用中,并确保抛出以便错误正确冒泡.

OR, you can leave the catch in the service call, and make sure to throw so that the error correctly bubbles up.

这篇关于Angular Catch 方法不适用于 $http get 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆