簡體   English   中英

AngularJS捕獲$ http操作的所有狀態代碼?

[英]AngularJS catch all status-codes for $http actions?

我的$http函數可以返回以下錯誤:

POST http://foobar.dev/foobar 500(內部服務器錯誤)

POST http://foobar.dev/foobar 401(未經授權)

有沒有辦法可以捕獲所有狀態代碼?

$http.post('/foobar', form)
    .success(function(data, status, headers, config) {
        console.info(data);
    })
    .error(function(data, status, headers, config) {
        console.error(data);
        if(status === 401) {
            $scope.setTemplate('show-login');
        }
        if(status === 500) {
            $scope.setTemplate('server-error');
        }
    }
);  

其中$scope.setTemplate()是Controller中設置視圖的函數。

但是我必須為每個error()函數執行此操作,並且有很多這樣的函數也沒有使它成為DRY代碼:P

我想要的是捕獲錯誤並根據錯誤中返回的狀態代碼執行操作。

僅供參考:我沒有使用Angulars $routeProvider()

您可以使用Angular $http攔截器,如@Dalorzo解釋:

var myApp = angular.module("myApp", [], ['$httpProvider', function($httpProvider) {

    $httpProvider.interceptors.push(['$rootScope', '$q', function($rootScope, $q) {
        return {
            'responseError': function(response) {
                var status = response.status;
                // Skip for response with code 422 (as asked in the comment)
                if (status != 422) {
                    var routes = {'401': 'show-login', '500': 'server-error'};
                    $rootScope.$broadcast("ajaxError", {template: routes[status]});
                }

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

然后在您的控制器中接收它:

$scope.$on("ajaxError", function(e, data) {
    $scope.setTemplate(data.template);
});

現在,您不必輸入每個error功能。

相反,這樣的事情怎么樣:

var routes = {'401':'show-login', '500': 'server-error'}; 
$scope.setTemplate(routes[status]);

其中routes是包含錯誤代碼和所需路由的字典。

這正是$http攔截器的用途。 請參閱此處的攔截器部分: $ http

基本上,您為所有$http請求創建通用功能,您可以在其中處理不同的狀態。 例如:

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2){
    return {
        response: function(response){
            // do something for particular error codes
            if(response.status === 500){
                // do what you want here
            }
            return response;
        }
    };
});

// add the interceptor to the stack
$httpProvider.interceptors.push('myHttpInterceptor');

我最初會說的是為$http服務創建一個裝飾器 ,或者創建一個服務作為$http服務的包裝器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM