chinabuffet
chinabuffet

Reputation: 5578

Injecting dependencies into AngularJS service

While reading through documentation on AngularJS services, I've stumbled across example services written like:

myApp.service('fooGetter', ['$http', function($http) {
    this.getFoo = function() {
        // use $http to get some foo
    }
}]);

where $http is injected to the service wrapper so it can be referenced from within the service instance that is created. What is the reason for array syntax that contains the list of parameters, which are then duplicated in the function parameters? I haven't been able to find a good explanation of the purpose of that, it's rules, and why it's necessary. The same service, written without that, like:

myApp.service('fooGetter', function($http) {
    this.getFoo = function() {
        // use $http to get some foo
    }
});

seems to have a perfectly fine automagic reference to that variable.

Upvotes: 1

Views: 136

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

This array syntax is necessary if you plan to minify your JS code, so that injection still works. Indeed, the minifier will change the name of the arguments of the anonymous function, and angular uses this name to know what to inject into the function. This alternative syntax solves the problem by defining the name of the arguments as strings, which won't be touched by the minifier.

Note that this is explained in the official documentation page about dependency injection.

Upvotes: 3

David Ferretti
David Ferretti

Reputation: 1400

If you use the syntax without the array containing the injected dependencies, angular uses reflection to read the arguments to your function. This works fine normally, but if you want to minify your code, your arguments will change name, and angular will stop working. Using the array syntax notation will allow angular to continue to find the correct dependencies even if your argument names change.

Additionally, if your injected services have really long names, you can inject them using the array syntax and give them an easier name to use in the function arguments list.

Example:

app.controller("MyCtrl", ["MyReallyLongUserServiceName", function(User) {
  User.doSomething();
}]);

Upvotes: 5

Related Questions