本文介绍了与服务的依赖$日志修饰导致循环依赖错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我写 $日志中的装饰,这样我可以自定义 $日志的功能包括调用第三方服务。第三方服务内喷射 $ Q 其内部活动。现在,这将导致循环依赖错误:

In my app i am writing a decorator for $log so that i can customize the functionality of $log including calling a third party service. The third party service injects $q for its internal activities. Now this causes circular dependency error :

未捕获的错误:循环依赖:$ Q< - tploggerService< - $日志< - $ exceptionHandler的< - $ rootScope

Uncaught Error: Circular dependency: $q <- tploggerService <- $log <- $exceptionHandler <- $rootScope.

由于 qProvider 使用 exceptionHandlerProvider 最终使用 logProvider 我的猜测是导致此。已装修的同时任何一个面临着类似的问题,有一个解决方案,以解决这个或不同的模式来解决这个问题?

Because qProvider uses exceptionHandlerProvider which ultimately uses logProvider which i guess is causing this. Has any one faced similar issues while decorating and is there a solution to work around this or a different pattern to work around the problem?

下面是code,鸭preciate你的帮助的一个简单的例子:

Here is a simple demonstration of code, Appreciate your help:

///Some third party APP
angular.module('SomeThirdPartyApp', []);

    tploggerService.$inject = ['$q']; //<-- $q is a dependency

    function tploggerService ($q) {

        this.info = function (data) {
            var deferred = $q.defer(); //Doing something...
            //....
            //....
     };
}

angular.module('SomeThirdPartyApp').service('tploggerService', tploggerService);

///--------------------------------------------------------------------------------
///MY APP
angular.module('decorApp', ['SomeThirdPartyApp']);

 angular.module('decorApp').config([
   '$provide', function ($provide) {
     $provide.decorator('$log', ['tploggerService','$delegate',
       function (tploggerService, $delegate) { //<--- Injecting tpLoggerService causes circular dependency error.
         var _info = $delegate.info;
         //It is no different even if we use $injector
         $delegate.info = function(){
             var args; //doing something with the arguments basically formatting massaging it.
             var customlogmessage; //doing something with args

             tploggerService.info(customlogmessage);
             _info.apply(null, args);
         }
         return $delegate;
       }]);
   }]);




    • JSBIN
    • Plnkr after $q removed
    • 推荐答案

      获取$ Q从服务内部:

      Get $q from inside of your service:

      function tploggerService ($injector) {
          var $q;
          this.info = function (data) {
              $q = $injector.get('$q');
              var deferred = $q.defer(); //Yes using defered object. some this performs some actions and some internal stuffs.
      
              //Doing something...
          };
      }
      

      这篇关于与服务的依赖$日志修饰导致循环依赖错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:45