I'm learning how to store API call response data in an AngularJS service. In all the examples that I saw, people used functions in the service to get or set values.
app.factory('dataFactory', function() {
let dataFactory = {};
let info;
dataFactory.setInfo = function(value){
info = value;
}
dataFactory.getInfo = function(){
return info;
}
return dataFactory;
});
But I realized that I could get and set values of variables in a service without the use of any functions.
app.factory('dataFactory', function() {
let dataFactory = {};
let dataFactory.info;
});
// Now I can get or set the value of this in my controller
app.controller('myCtrl', [dataFactory, function(dataFactory) {
dataFactory.info = "Value"; // setting the value
let test = dataFactory.info; // getting the value
}])
I would like to know if my approach could potentially lead to any problems. Is it considered a bad practice and if so why?
Preference to data accessors (getters and setters) over exposing a property directly is neither specific to AngularJS nor to JavaScript. Is generally a common practice in the object oriented programming.
One of the main reasons to prefer getters and setters over the direct access to a property is data encapsulation. When the data is defined as a local variable in the lexical environment of the service function (let info;
) it is not possible to access it from outside (for example from controller).
Data accessors also give you a flexibility to add data access logic. For example you may want to implement some checks when the getter is called and make a decisions whether to return the data or not. Likewise, in the setter you may verify that the data (the setter was called with) meets the requirements and throw an error if it's not.
Further you may want to check this answer to see many other benefits getters and setters may provide.