When working with AngularJS it is very common to have applications where services contain only HTTP calls to the server that will store the data. However, in an application where we will not have a server our service can be responsible for many business logic (do not worry about the code being visible to the user) and because of this one service can call another and vice versa (this is bad practice) .
Imagine the following situation:
angular.module('app').service('logAPI',[ function('fileManager') {
var _logList = [];
var LogMessage = function(system, type, message, value, now) {
this.system = system;
this.type = type;
this.message = message;
this.value = value;
this.time = now;
};
this.scheduleLogMessage = function(system, type, message, value) {
if (_logList.length < 300) {
var now = utilAPI.getFormattedTime();
var log = new LogMessage(system, type, message, value);
_logList.push(log);
}
};
this.processLog = function() {
if (_logList.length >= 200) {
fileManager.upload(_logList[0]);
}
};
}])
.service('fileManager',[ function('storageAPI') {
var upload = function(obj) {
storageAPI.upload(obj).then(function success() {
logAPI.scheduleLogMessage('a', 'a', 'a', 'a');
}, function error() {
logAPI.scheduleLogMessage('a', 'a', 'a', 'a');
})
}
}])
.controller('appCtrl', ['', function('logAPI'){
while(true) {
logAPI.processLog();
}
}]);
The angularJS will accuse of circular dependency. There are ways to circumvent this and the angular 'ignore' this dependency, but is this a bad practice? Should we avoid?
Editing: Improving the example
My logAPI is responsible for managing all log generated by the system and after an amount of message X, it begins to upload these logs. When the upload is done, it can also generate log to record what happened. In general, everything in my system generates LOG and because of this, I can not think of a way to break this dependency.