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

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Is there a CSS rule that can alter the appearance of links once they have been clicked on a different webpage?

Just starting out here. Imagine I have 4 distinct links leading to the same webpage - is there a way to modify the properties of the destination page depending on which link was clicked? For instance, clicking on link1 changes the background color of the d ...

What is the best way to save an integer in HTML's localStorage instead of a string?

I've encountered an issue while using the localStorage feature in a game I'm developing. Specifically, the money variable should be increasing by 1 every second. Here's a snippet of my code: var money = 0; window.onload = function () { ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

Querying the sqlite-3 database fails to transfer data to a JavaScript array

I encountered an issue while working on a NodeJS project that involves fetching film names and descriptions from an Sqlite-3 file when a user sends a GET request to /films. For some reason, I am unable to push the object to an array properly. Despite my ...

Troubleshooting Problem with Updating Bootstrap Datepicker in AngularJS

Having trouble updating the date field in the database from my Angular page. Unable to bind the modified date to the database, as the item.ReimbDate still holds the old value. Currently using a bootstrap datepicker for this process. <input type="text" ...

Why do my paths encounter issues when I alter the manner in which I deliver my index.html file?

I recently made a decision to change the method of serving my index.html file from app.use('/', express.static(__dirname + '/..')); to app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/../index.htm ...

Sequelize error: Foreign key mentioned, yet not found in the table

I recently started using Sequelize and have been relying heavily on the documentation available here. The documentation mentions the importance of using hasOne(), hasMany(), and belongsTo() to automatically add foreign key constraints. In my case, I am wor ...

Unable to animate a second click using jQuery/CSS

I'm having an issue with animating on click using CSS. The animation works fine on the first click, but it doesn't work on the second click. This is because the click event is being overridden by jQuery to enable the dropdown menu to open onClick ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Display the current count of selected radio buttons in real-time

I am working with radio buttons that are generated dynamically using a 2D array within a while loop. I want to display the number of radio buttons checked when one is clicked. Here are my radio buttons: $n=0; while($row=mysqli_fetch_row($rs)){?> <f ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

What are the steps to generate a service instance?

I am working on a unique service: (angular .module('app.services', ['ngResource']) .factory('MyService', [ /******/ '$resource', function ($resource) { return $resource('myurl'); ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

What causes a 404 error when using a router in Express/node.js?

I've recently created an Express app and set up a custom route (/configuration). However, when I try to access http://localhost:3000/configuration, I keep getting a 404 Not Found error from the server. I've reviewed the code but can't seem t ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...