繁体   English   中英

使用带有$ exceptionHandler的$ http

[英]Using $http with $exceptionHandler

我想发布角度应用程序中发生的错误。

我按照相关问题中给出的方法,如答案所示,我注入了$ injector,然后从那里获得了$ http服务。 但行

未捕获的错误:循环依赖:$ http < - $ exceptionHandler < - $ rootScope

继续前进。

这是问题的小提琴

与相关代码:

var mod = angular.module('test', []);
mod.config(function ($provide) {
    $provide.decorator("$exceptionHandler", ['$delegate', '$injector',             function ($delegate, $injector) {
      var $http = $injector.get("$http");
    }]);
  });
mod.controller('testCtrl', function ($scope) {
  });

如果你评论该行

var $ http = $ injector.get(“$ http”);

循环依赖性错误消失了。

我想我在理解中遗漏了一些东西。 我究竟做错了什么? 毕竟,这似乎对其他人有用。

关于如何实现我的“向服务发布错误”的初始目标的任何建议也受到欢迎。

感谢大家

将进样器代码包装在函数中

var mod = angular.module('test', []);
mod.config(function ($provide) {
    $provide.decorator("$exceptionHandler", ['$delegate', '$injector',function ($delegate, $injector) {
           return function (exception, cause) {
              var $http = $injector.get("$http");
           }
    }]);
  });

  mod.controller('testCtrl', function ($scope) {
  });

你可以这样做。

这将打破您的循环依赖性错误,您也可以实现您的目标。

如果我没有错,那么你只想在异常处理程序中调用Web服务。

var httpCallOnAngularError = angular.module('exceptionTestApp', []);

/*httpCallOnAngularError.factory('$exceptionHandler', function () {
 return function (exception, cause) {
        alert(exception.message);
    };
});*/

httpCallOnAngularError.config(function ($provide) {
    $provide.decorator("$exceptionHandler", function ($delegate, $injector) {
        return function (exception, cause) {
            var $rootScope = $injector.get('$rootScope');
            $delegate(exception, cause);
            $rootScope.logAngularError();
            alert(exception.message);
        };
    });
});
httpCallOnAngularError.run(function ($http, $rootScope) {
    $rootScope.logAngularError = function () {
        //Call your webservice here.
        $http.get("http://jsonplaceholder.typicode.com/posts/1")
                .success(function (response) {
                    console.log(JSON.stringify(response));
                });
    };

});

httpCallOnAngularError.controller('exceptionTestCtrl', function ($scope) {
    throw {message: 'Log this error by calling webservice.'};
});

您可以通过此模板进行验证。

<div ng-app="exceptionTestApp" ng-controller="exceptionTestCtrl">
</div>

Webservice在$ exceptionHandler中调用异常处理程序$ http

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM