1

Let's say I create an AngularJs service. I attach it to my module:

angular.module('fooModule').service('myService', function(){
    var service = {
        logSomething: function() {
            console.log('Service logged something');
        }
    };
    return service;
});

Whatever. It's there - same with constants, factories, providers, etc. Why do I need to then inject this service, constant, etc into my controllers? Is it essentially the same principle as "using" in C# - the only purpose being avoiding conflicting variable/function names? That doesn't seem to make sense since I still have to write myService.logSomething() which clears up the whole namespace issue.

Or does it somehow speed up loading? I don't see how that would be though.

Daniel Cottone
  • 3,589
  • 21
  • 37
VSO
  • 8,950
  • 19
  • 69
  • 148

1 Answers1

1

You haven't actually injected this service into anything yet; it is just a singleton at this point. You have registered it with your angular module, yes, but nothing else in your module knows about it. It's not available until you actually inject it. In a very abstract way, you could think about dependency injection in Angular like using or import, but it's really more like supplying an initializing variable in a constructor (actually, this is exactly what it is).

If you are wondering why dependency injection might be a good design practice in general, this post should be of interest to you.

Community
  • 1
  • 1
Daniel Cottone
  • 3,589
  • 21
  • 37