Akash khan Akash khan - 5 months ago 19
AngularJS Question

Angular Factory return null but shows result in console

I have a factory service and here a method getCount. When I call this method in my controller it's return null but I have tested in my factory service by printing data in the console. It shows data in console but not return any value to my controller.

obj.getCount = function(table, field) {
var query = "select count(" + field + ") as total from " + table + "";
$db.query(query).then(function(results) {
console.log(results.rows.item(0).total); // here show data in console
if (results.rows.item(0).total) {
return results.rows.item(0).total;
} else {
return 0;
}

});
}


In my controller

$scope.totalAccount=DBFactory.getCount('accounts','id');

Lee Lee
Answer

Return the $db.query.then like so:

obj.getCount = function(table, field) {
    var query = "select count(" + field + ") as total from " + table + "";
    return $db.query(query).then(function(results) {
        if (results.rows.item(0).total) {
            return results.rows.item(0).total;
        } else {
            return 0;
        }
    });
}

Then change your controller code to:

DBFactory.getCount('accounts','id').then(function(data) {
    $scope.totalAccount = data;
});
Comments