Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$log decorator with a service dependency causes circular dependency error

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 :

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

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?

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
like image 877
PSL Avatar asked Nov 01 '22 00:11

PSL


1 Answers

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...
    };
}

Updated Plunk

like image 60
Marc Kline Avatar answered Nov 08 '22 06:11

Marc Kline