My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin.
While each factory works correctly when used individually, I encounter issues when trying to integrate LDB within Api's functions as it fails to return data.
Below is the code for LDB. Please note that 'db' is defined in the root scope as the sqlite database.
.factory('ldb', function($cordovaSQLite) {
function currentSite(){
return $cordovaSQLite.execute(db,"SELECT * FROM sites WHERE id=1");
}
return{
current: function(){return currentSite()}
}
}
And here is the code for Api.
.factory('api', function($http,config,ldb) {
function getLastEvent(){
ldb.currentSite().this(function(res){
var siteid = res.rows.item(0).siteid;
var sitepin = res.rows.item(0).sitepin;
if(siteid != null && sitepin != null){
$scope.lastEvent = $http.post(config.apiURL, {siteid: siteid, sitepin: sitepin, action: 'getLastEvent'});
return true;
}
else{ return {"AlertType":"OP","Time":"00:00","Date":"No Site"};}
return {"AlertType":"OP","Time":"00:00","Date":"No Site"};
})
}
return{
lastEvent: function(){return getLastEvent()}
}
To call Api in my controller, I use the following method.
app.lastEvent().then(function(res){
if(res.data == "Invalid Details Provided!"){$scope.lastEvent = {"AlertType":"OP","Time":"Invalid Login","Date":""};}
else if(res.data != null){ $scope.lastEvent = res.data[0];}
else{$scope.lastEvent ={"AlertType":"OP","Time":"Error","Date":""}}
})