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?
Providers, factories, services, seems more complex than it actually each. Each is a specialized version of the other allowing you to accomplish the same thing with less code, if it meets your need.
For example if all you are returning is a literally value like a number or a string you can use value and accomplish that in one line of code. You can also go up the chain and do it using a factory, but you would be writing less code.
On the other hand if wanted to calculate a value based on another value that you get from the server. Well you can't do that using value therefore you have to go one level up to a factory.
So on and so on up the chain. The following blog post goes into that in detail and gives you several examples:
Here is a high level image from that same post illustrating what I said above: