1
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 may be responsible for many business logic (do not worry about the code being visible to the user) and because of this one service may 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. Are there ways to circumvent this and the angular 'ignore' this dependency, however, this is bad practice ? We must avoid?
Editing: Improvement of the example
Man logAPI is responsible for managing every log generated by the system and after an X amount of message, it starts uploading those logs. When the upload is done, it can also log in to record what happened. In general, everything in my system generates LOG and because of that, I can’t think of a way to break this dependency.
Tlz help, Memory Management
– Guilherme Lautert
I made a change to the answer. Make sure it meets what you need.
– Gabriel Câmara