I created an AngularJS factory that I reuse for data access:
app.factory('abstractFactory3', function ($http) {
function abstractFactory3(odataUrlBase) {
this.odataUrlBase = odataUrlBase;
}
abstractFactory3.prototype = {
getList: function (odataOptions) {
return $http.get(this.odataUrlBase, {
params: odataOptions
});
},
get: function (id, odataOptions) {
return $http.get(this.odataUrlBase + '/' + id, {
params: odataOptions
});
},
insert: function (data) {
return $http.post(this.odataUrlBase, data);
},
update: function (id, data) {
return $http.put(this.odataUrlBase + '(' + id + ')', data);
},
remove: function (id) {
return $http.delete(this.odataUrlBase + '(' + id + ')');
}
};
return abstractFactory3;
});
Reading a brief write-up on the differences between Angular services, factories and providers, I am a bit confused as to what this factory actually is, based on those definitions.
In Summary:
Services: provided with an instance of the function.
Factories: the value that is returned by invoking the function reference passed to module.factory.
Providers: provided with ProviderFunction().$get(). The constructor function is instantiated before the $get method is called
To use this factory, it is initialized with an ODada path:
var dataFactory = new abstractFactory3("/odata/ContentType");
dataFactory.getList(odataParams)
.success(function (result) {
options.success(result);
})
.error (function (error) {
console.log("data error");
});
Since I'm newing up the abstractFactory3
, I am now provided with an instance of the function (like a service)... Initialization provides me with an instance of the function - service, right? However, a value is returned by calling a method - .get(), .getList(), .insert(), .update(), .remove()
. Is considered to be similar to a provider's ProviderFunction().$get()
?
Can someone please clarify this?
Factories return the result of invoking the function - in your case, its just a function. So, when the factory is injected, it is also just a function. That is why you can 'new' up your function after it has been injected (like in your example). You are correct, this is essentially what a service is.
No, a provider.$get is not similar to calling .getList(), .insert(), etc. The result of provider.$get is what is injected by the $injector. For factories, it is the result of invoking the factory function. For services, it is the result of new'ing up the service's constructor function.
Provider.$get is more flexible - it can return whatever you want (which means you can inject whatever you want).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With