Reputation: 607
.factory("user", userService);
function userService($q, $http) {
function User (){
//....
}
return User;
}
or
.factory("User", ["$q", "$http", function ($q, $http) {
var User = {
//....
}
return User;
}])
I often see both depending of the situation (or rather depending of the author), but I've been wondering for quite a long time now (since I've begun learning Angular), what makes it different, and if I can use one or the other without changing anything.
I usually use the first one and following the logic because I find it easier, and because I'm confused with the second one. I may have made mistakes but that's why Im asking for some help.
Thanks !
Upvotes: 0
Views: 33
Reputation: 3630
The second code snippet in your question is the one that I'd recommend you to use for all your angularjs services.
Angular framework offers Dependency Injection (DI) feature out of the box that can be used when defining components such as services, directives, filters, animations or when providing run and config blocks for a module.
If you define the dependencies without using an array of string in your angular app, then you are doing it wrong. This way of registering the dependencies will work well for non minified version of the JavaScript source file.
But if you intend to minify the files for production, which everyone must, then all those (dependency) arguments will be changed to something really random which angular will not be able to map to any registered component. So ultimately, an error will be thrown by the framework.
To avoid this mistake, one can just make sure to always use an array of type string to instruct the dependencies. Read this in more detail. If you are your own then you can maybe keep this tip in mind. However, if working in a team, it is good to configure this using the options below so that everyone in the team follows this. If not, then they will encounter an error.
I'd recommend you to use strict DI mode.
How to enable strict mode? This mode can be enabled using two options as mentioned below.
Option-1:
<div ng-app="myApp" ng-strict-di>
<!-- your app here -->
</div>
Option-2:
angular.bootstrap(document, ['myApp'], {
strictDi: true
});
Learn why is strict DI mode good for your AngularJS app in my blog post.
Upvotes: 1
Reputation: 4443
The first form will not work with minification. The second form is required when minification is used. The reason for this is that the AngularJS injector uses the function parameter names to resolve the $q
and $http
dependencies in the first form. If the function parameter names are changed (e.g., by minification), that will fail. The second form relies on the strings "$q"
and "$http"
, which will not be changed by minification.
This is discussed in step 7 of the AngularJS tutorial.
Upvotes: 0