本文介绍了在角使用拦截器的错误处理通用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用了棱角分明1.08,所以我需要使用 responseInterceptors

I'm using Angular 1.08, hence I need to use responseInterceptors.

首先,code。

国米preTER:

app.factory('errorInterceptor', ['$q', 'NotificationService', function ($q, NotificationService) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success
            return response;
        }, function (response) {
            // do something on error
            alert('whoops.. error');
            NotificationService.setError("Error occured!");

            return $q.reject(response);
        });
    }
}]);

app.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('errorInterceptor');
});

NotificationService:

NotificationService:

app.service("NotificationService", function () {
    var error = '';

    this.setError = function (value) {
        error = value;
    }

    this.getError = function () {
        return error;
    }

    this.hasError = function () {
        return error.length > 0;
    }
});

指令错误框:

app.directive("errorBox", function (NotificationService) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div data-ng-show="hasError">{{ errorMessage }}</div>',
        link: function (scope) {
            scope.$watch(NotificationService.getError, function (newVal, oldVal) {
                if (newVal != oldVal) {
                    scope.errorMessage = newVal;
                    scope.hasError = NotificationService.hasError();
                }
            });

        }
    }
});

问题:当我使用&LT;错误盒&GT; 在多个位置,这些框将显示错误消息。这不是我的意图。我想只显示错误对话框,在其中发生异常。

The problem: When I use <error-box> at multiple places, all these boxes will display the error message. This is not my intent. I'd like to show only the error-box where the exception occurs.

例如,我有一个指令,它显示了交易的列表。当获取的交易失败,我想表明这是该部声明的错误对话框。
我也有一个指令,在那里我可以编辑一个客户。该指令还包含错误框标记。

For example, I have a directive which shows a list of transactions. When fetching the transactions fails, I want to show the error-box which is declared in that part.I also have a directive where I can edit a customer. This directive also contains the error-box tag.

在保存时的客户失败,同时显示错误盒发生什么,但是,我只想显示客户的错误对话框。

What happens is when saving a customer fails, both error-boxes are displayed, however, I only want the error-box of the customer to be displayed.

是否有人有一个想法,以实现这个?

Does someone has an idea to implement this?

推荐答案

角服务是单身的对象,如角文档的。这意味着,只有角创建一个服务的一个单一的全局实例,每当请求给定的服务使用相同的实例。这意味着,角永远只能创建你的 NotificationService 服务单一实例,然后将一个实例,提供给你的 errorBox 指令。所以,如果一个指令更新 NotificationService 的误差值,那么所有的&LT;错误盒指令将得到该值。

Angular services are Singleton objects, as described in the angular docs here. This means that Angular only creates one single "global" instance of a service and uses that same instance whenever the given service is requested. That means that Angular only ever creates one single instance of your NotificationService services and then will supply that one instance to every instance of your errorBox directive. So if one directive updates the NotificationService's error value, then all of the <error-box directives will get that value.

所以,你将不得不无论是对每种类型的错误(即 TransactionNotification CustomerNotification 等)或不同的方法添加到您的主 NotificationService ,将允许您设置只有特定的警报(如 NotificationService.setCustomerError() NotificationService.setTransactionError())。

So, you're going to have to either create multiple notification services for each type of error (ie TransactionNotification and CustomerNotification, etc) or add different methods to your main NotificationService that would allow you to set only specific alerts (such as NotificationService.setCustomerError() or NotificationService.setTransactionError()).

这些选项都不是特别人性化,也不干净,但我相信,(给你已经设置了服务的方式),这是做到这一点的唯一方法。

None of those options are particularly user-friendly nor clean, but I believe (given the way you've set up your service), that's the only way to do it.

更新:考虑这件事之后,我可能会建议只是删除你的整个 NotificationService 类,只是使用 $范围事件通知您的&LT;错误盒&gt;在发生错误元素:

UPDATE: After thinking about it, I might suggest just dropping your whole NotificationService class and just using $scope events to notify your <error-box> elements when an error occurs:

在你的'errorInterceptor

app.factory('errorInterceptor', ['$q', '$rootScope', function ($q, $rootScope) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success
            return response;
        }, function (response) {
            // do something on error
            alert('whoops.. error');
            var errorType = ...; // do something to determine the type of error
            switch(errorType){
                case 'TransactionError':
                    $rootScope.$emit('transaction-error', 'An error occurred!');
                    break;
                case 'CustomerError':
                    $rootScope.$emit('customer-error', 'An error occurred!');
                    break;
                ...
            }

            return $q.reject(response);
        });
    }
}]);

然后在你的 errorBox 指令:

link: function (scope, element, attrs) {
        var typeOfError = attrs.errorType;
        scope.$on(typeOfError, function (newVal, oldVal) {
            if (newVal != oldVal) {
                scope.errorMessage = newVal;
            }
        });

    }

然后在您的视图:

And then in your view:

<error-box error-type="transaction-error"></error-box>
<error-box error-type="customer-error"></error-box>

这是否有道理?

这篇关于在角使用拦截器的错误处理通用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:17