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

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

问题描述

我正在尝试从控制器中整齐地管理服务功能调用,同时处理来自API的错误.

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

但是,当我执行以下操作时,即使API返回403或404,我仍会在控制台中获得this is showing even with 403 and 404 errors.

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获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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