Accessing a factory from within another in AngularJS Ionic

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

Answer №1

Your code contains some errors that need to be addressed: Within the 'api' factory, you have written ldb.currentSite().this(... instead of ldb.current().then(....

It is important to note that the 'ldb' factory returns a function called current().

Additionally, keep in mind that $cordovaSQLite.execute() operates asynchronously and therefore returns a promise with the method then(), not this().

You mentioned that the db is defined in the "root scope." Could you clarify what you mean by this? Is it a property of $rootScope? If so, you should reference it as $rootScope.db.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access a specific element within an ng-grid

My grid options include: $scope.ngOptions = { data: 'data', columnDefs: [ {field: 'Status', displayName: "Status", cellTemplate: selectTableTemplate, enableCellEdit: true}, {cellTemplate: &apos ...

Challenges encountered when bringing in modules from THREE.js

Is there a way for me to import the custom geometry file called "OutlinesGeometry.js" from this link? I've attempted to import it like this: <script type="module" src="./three/build/three.module.js"></script> <scrip ...

Using JQuery to access the element within a span

I am completely new to jQuery and still learning as I go. Here is a snippet of the code I'm working on: <div class = 'buttons'> <span> <input type='button' value='BUTTON1' id='button1'> ...

Having a concise way to submit forms with Javascript and JQuery

Seeking a more concise way to submit form data to Electron in JSON format as a beginner in JavaScript and jQuery. How can this code be rewritten for brevity? <section> <input id="server" type="text" placeholder="Server"> <i ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

Developing a custom styling class using JavaScript

Looking to create a custom style class within JavaScript tags. The class would look something like this: #file-ok { background-image: url(<?php echo json.get('filename'); ?>); } Essentially, the value returned from the PHP file (json ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

Construct a new array within a JavaScript constructor function

I have been working on setting up a constructor and trying to initialize an array inside the object that will be created. This specific array is meant to hold multiple objects. function Cluster3DObject(name){ this.name = name; ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

Can Google Maps be initialized asynchronously without the need for a global callback function?

Currently, I am working on developing a reusable drop-in Module that can load Google Maps asynchronously and return a promise. If you want to take a look at the code I have constructed for this using AngularJS, you can find it here. One issue I have enco ...

Using jQuery to align a div element to the top of the viewport

Is there a way to keep the #lightbox div positioned at the top of the viewport consistently? $(document).ready(function(){ $('.mehr').click(function() { $("body").css("overflow", "hidden"); $('#lightbox').css({'visibil ...

Rewriting Rules for WordPress site on Apache Server

Looking to redirect Facebook crawlers to a static page on my AngularJS website due to the need to work with og:meta. Using Wordpress as the back-end, currently utilizing the following .htaccess: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngi ...

Retrieve the customized attribute from the chosen option within the datalist

Is there a way to retrieve the custom attribute "location" of an option selected from a datalist and display it? I understand that for a select element we can use selectedIndex, but how can this be achieved with datalist? <!DOCTYPE html> <html&g ...

What is the reason for jQuery scripts not functioning properly when the scripts are placed above the jQuery library?

this script is functioning correctly: <div class="demo-gallery" data-pswp-uid="1"> <a class = "delete_button">click</a> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <script> ...

Is it possible to refresh the bootstrap datatable automatically every minute?

I have implemented a bootstrap server-side datatable in my AngularJS application and now I need to refresh the data of that table every minute. Can anyone provide guidance on how to achieve this? Here is the code snippet I am currently using: HTML: <t ...

Error: The property 'open' is not defined in the mdMenu object

Encountered a bug while working with angular-material design... When using md-menu, if a sub menu item is opened (as shown in the image) and then hovering over a non-subMenu item (menu item), it throws an error "Cannot read property 'open' of nul ...

The favicon appears broken upon opening a new tab

Usually, I use a favicon PNG file for my website. It works perfectly and I can see my favicon on the browser tab. However, when I open a PDF document in a new page from my Angular app, I notice that there is a broken icon on the browser tab. Here is how I ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

Instructions on extracting a random element from an array and continue removing elements from the array until it is completely empty

I am attempting to utilize either jquery or javascript to remove a random item from an array until it is empty. Each time I remove an item, I want to log it to the console. My goal is to create elements with random images from the specified array until all ...