Reputation: 54016
Learning angular from different resources on internet makes really confusing. everyone using different kind of patterns to write functions .Kindly throw some light on this .provider concept
I have tried .provider
with 4 different pattern and all are working
pattern A : using all function inside return
app.provider('other', function() {
name ="Default";
return {
$get: function () {
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
}
},
setName: function (newName) {
name = newName;
}
};
});
pattern B : using this
and differ the $get and other methods
app.provider('other', function() {
this.name ="Default";
this.$get = function () {
var name = this.name;
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
};
};
this.setName = function(name) {
this.name = name;
};
});
pattern C : also found somewhere using array [ ]
just before the function which has return
this.$get = [function () {
var name = this.name;
return {
sayHello: function () { console.log('provider example say my name is :' + name )}
}
}];
Pattern D: with .factory and then functionNameProvider.$get.methodName() with .config
app.factory('alpha', function(){
var c = ['Cadbury','Perk','Dairy Milk'];
return {
sayHello: function() { console.log('Hello, I am from Provider');},
getAllData: function() { return c; }
};
});
then
app.config(['alphaProvider',function(alphaProvider) {
console.group('Checking Factory Pattern');
alphaProvider.$get().sayHello();
var cdata = alphaProvider.$get().getAllData();
console.log(cdata);
console.groupEnd();
}]);
created a jsfiddle for the same, Kindly tell me which is correct/preferred way?
Upvotes: 2
Views: 97
Reputation: 4385
Both patterns A and B are correct ways of creating the provider/service.
The function
you pass to the provider()
method is a constructor of the provider instance. Provider instance is simply an object with $get
method. You have two options on how to instantiate it:
this
syntax and return nothing from constructor (pattern B). In this case angular will create a provider instance as a new Object
and run your constructor against it (with this
bound to it).The pattern C is the Inline Array Annotation - a way to specify the dependencies of your component/function. The array should contain the names of dependencies followed by the function
where you want them injected. Can be used with both A and B approaches.
UPDATE
As pointed out by @estus, the B approach is more efficient because in case of A the new Object
is also created but never used.
Upvotes: 3