Ad

Calling One Factory Within Another AngularJS Ionic

I've written an ionic app with two factory one called Api that handles API calls and one called ldb(local database) that handles interaction with a local Sqlite database using the CordovaSqlite plugin.

When I try to use either factory separately they function as intended however when I try to use ldb within Apis functions it doesn't return data.

Here is my ldb code. Please note 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 my api code

.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()}
}

I am calling api in my controller like this.

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":""}}
})
Ad

Answer

There are some errors in your code: in 'api' factory you wrote ldb.currentSite().this(... instead of ldb.current().then(....

In fact the 'ldb' factory returns a function named current().

Besides, pay attention, $cordovaSQLite.execute() is an asynchronous operation so it returns a promise which has the method then() not this().

Finally you said db is defined in the "root scope": what do you mean? It is a property of $rootScope? If yes you have to reference it with $rootScope.db.

Ad
source: stackoverflow.com
Ad