Imagine a scenario where an Angular factory holds a substantial amount of raw data (referred to as _fakeData), and I aim to reveal a specific portion of the data based on the parameters passed during initialization (known as _exposedData).
Currently, I have implemented a method called init(language) that sets this._exposedData to a certain value depending on the language parameter. Subsequently, all other factory methods operate based on _exposedData.
However, to make this approach effective, I must first invoke the init() method and then constantly check if it has been called before using any other factory methods, making the process quite cumbersome.
I acknowledge that my current solution is not very efficient, and I seek advice on a better way to organize and structure my factory. Can someone provide guidance in this regard?
angular.module('testApp', [])
.factory('TestFactory', function() {
return {
//raw data set that should not be accessed or modified
//access should be done through _exposedData instead
_fakeData: {
javascript: 'blah blah',
ruby: 'blah blah blah',
python: 'blah blah blah blah'
},
_isInitialised: false,
init: function(language) {
if (this._fakeData[language]) {
this._exposedData = this._fakeData[language];
this._isInitialised = true;
return this;
}
throw new Error('Cannot initialize');
},
getData: function() {
this._checkInitialised();
return this._exposedData;
},
//checks whether init() has been called
_checkInitialised: function() {
if (!this._isInitialised) {
throw new Error('Not initialized');
}
}
}
})
.controller('TestCtrl', function($scope, TestFactory) {
console.log(TestFactory.init('javascript').getData());
})