AngularJS-处理$http错误



我有一个指令,我正在向其中注入一个服务,该指令对后端服务进行$http调用。

您通常如何处理404/401/HTTP错误?我正在寻找最佳实践模式。

$http在遇到HTTP错误时是否会狼吞虎咽地拒绝承诺?

这就是我到目前为止所做的,它似乎还可以,但我不确定我是否正在按照推荐的方式进行:

服务

app.service('helpService', ['$http', function ($http) {
    return {
        getHelpUrl: function (pageUrl) {
            return $http.post('Home/GetHelpUrl', { pageUrl: pageUrl });
        }
    }
}]);

指令

app.directive('helpLink', ['$location', 'helpService', function ($location, helpService) {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        template: function (elem, attrs) {
            return '<a ng-href="{{helpUrl}}" ng-show="showLink" target="_blank">Help?</a>';
        },
        link: function (scope, elem, attrs) {
            scope.showLink = false;
            helpService.getHelpUrl($location.path()).success(function (data) {
                scope.helpUrl = data.helpUrl;
                scope.showLink = true;
            });
        }
    }
}]);

success方法一样,也有一个通过$http定义的error(function(data, status, headers, config)方法。

这是文档中的示例

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

您可以使用它来捕获错误

如果您想捕获所有错误,您可以查看Interceptors。请查看文档。您也可以在.then方法中使用错误回调。(这将取代您的.success方法),因为$http返回一个promise(请参阅$q promise api):

拦截器可以注册如下:

app.config(function($httpProvider){
    $httpProvider.interceptors.push('connectionInterceptor');
});
app.factory('connectionInterceptor', function ($q) {
    return {
        'requestError':function(rejection){
             //do something general (global)
             //send a rejection
        },
        'responseError': function (response) {
             //do something general (global)
             //send a rejection
        }
    };
});

相关内容

最新更新