1

I have an angular application which is based around a core service.

To ease debugging, I'd rather not have to remember the following invocation (from how to debug angular services in browser):

tasks = angular.element(document.body).injector().get('tasks');

So my first thought was to stick this statement in a script tag in my index.html, but if I do that, it fails with

Uncaught TypeError: Cannot read property 'get' of undefined

I was looking for the equivalent of jQuery's document ready, but it seems that's not the Angular way. The Angular way seemed to be a construct like this (from https://plus.google.com/+MicahGodbolt/posts/CiKyN2YUafM):

angular.module('mushin', []).run(function() {
  window.tasks = angular.element(document.body).injector().get('tasks');
})

This however gives me the same error.

What's the proper way to get an angular service into a javascript variable for debugging in the console?

Community
  • 1
  • 1
Thomas Vander Stichele
  • 36,043
  • 14
  • 56
  • 60

1 Answers1

0

You can attach the tasks service to the widow object anywhere you use it. In your example with the run() method above you just need to add the tasks service as a dependency to the function like so:

angular.module('mushin', []).run(function(tasks) {
  window.tasks = tasks;
});

It's failing now because at the point of entry to the run method there isn't anything yet bound to the body element so you don't have an injector yet.

The more "angular way" to do this would be to also depend on the $window service so your callback becomes:

angular.module('mushin', []).run(function($window, tasks) {
  $window.tasks = tasks;
});
craigb
  • 16,827
  • 7
  • 51
  • 62
  • Thanks for the detailed answer, that makes sense! I no longer get that console error, but instead I get `Uncaught Error: [$injector:unpr] Unknown provider: tasksProvider <- tasks`. This is even though the application works, including the tasks service. Just to test, I replaced tasks with $scope (which is an angular built-in) but I get the same failure. This suggests that at this point the dependencies can't be looked up yet? – Thomas Vander Stichele Aug 09 '14 at 19:52
  • Without seeing all the code, theres a couple things I'd check: (1) make sure you only have one `angular.module('mushin', [])` as this defines the module and its dependencies. If you have another call like this it is re-defining the module. (2) make sure that empty array `[]` in the above module definition is correct i.e. your `tasks` service is defined in the same `mushin` module. If not e.g. it's in `mushin.services` or something, then it needs to be added to the dependencies list for the module definition. – craigb Aug 12 '14 at 20:07