Is it possible to use $ logProvider to enter the module configuration block?

I want to print log messages to the console when debugging. Works great in controllers, but cannot make it work in the module configuration block, for example.

angular.module('MyApp', []) .run(function($state){ // run stuff here }); .config(function($logProvider){ $log.debug('Config debug message'); }); 

I get an error message:

 error TypeError: Cannot read property 'debug' of undefined 

Is it possible to use logProvider in the module configuration block?

+5
source share
1 answer

$logProvider , available during the configuration phase, is used to configure the log service, or you can enter $provide to change / use the logservice service behavior using decorators . The journal service itself has not yet been created in your MyApp module. Instead, you can get a log instance from the ng kernel and use it for debugging.

You can do: -

  .config(function(){ var $log = angular.injector(['ng']).get('$log') $log.debug('Config debug message'); }); 

$logProvider.$get will provide you with a constructor for logservice, you can instantiate it yourself by calling $injector.instantiate($logProvider.$get) , but the problem is that it has a dependency on a window service that has not yet been created, so ultimately your registrar

Another hacked way would be to force angular to start the logger by adding a decorator to the configuration block, which you can configure as the first configuration block before any configuration logging is required, after which you can execute ctor with $logProvider getter and get a logger instance.

 .config(function($provide){ //Just a dummy decorator $provide.decorator('$log', function($delegate){ return $delegate; }); }).config(function($logProvider){ //get logger instance var log = $logProvider.$get(); log.debug("Got it"); }); 

Plnkr

+16
source

Source: https://habr.com/ru/post/1203177/


All Articles