1

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.

2 Answers 2

5

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();
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Got it... thanks! will accept answer but have to wait a few minutes before it lets me...
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.