Angular Service Calling Another Service
I'm making a simple Angular app to manage incomes. The incomes come from projects that I store in json (for testing purpose). So, basically, I use a service in Angular to get this
Solution 1:
This is how async call works: If Incomes
service data populates by async way, therefore it must return promise as well.
I would create some method buildAndGetIncomes
that will call Projects.async()
and when data is fetched -> return new promise to controller:
facturateApp.service('Incomes', function(Projects, $q){
varself = this;
var deferred = $q.defer();
var incomes = [];
self.buildAndGetIncomes = function(){
Projects.async().then(function(d) {
var projects = d;
angular.forEach(projects, function(project){
if(typeof(project.account.accountAmount) == 'number' && project.account.accountAmount > 0){
var newIncome = {};
newIncome.projectName = project.projectName;
newIncome.clientName = project.clientName;
newIncome.typeIncome = "Accompte";
newIncome.amount = project.account.amountAccount;
newIncome.date = project.account.accountDate;
newIncome.notes = project.account.accountType;
incomes.push(newIncome);
}
});
angular.forEach(projects, function(project){
if (typeof(project.total.totalAmount) == 'number' && project.total.totalAmount > 0){
var newIncome = {};
newIncome.projectName = project.projectName;
newIncome.clientName = project.clientName;
newIncome.typeIncome = "Accompte";
newIncome.amount = project.total.totalAmount;
newIncome.date = project.total.totalDate;
newIncome.notes = project.total.totalType;
incomes.push(newIncome);
}
});
deferred.resolve(incomes);
});
return deferred.promise;
};
});
and from controller we call :
Incomes.buildAndGetIncomes().then(function(incomes) {
// ...
}, function(error) {
// ..
});
Post a Comment for "Angular Service Calling Another Service"