Inactive function

I have a function that inserts my articles and I call this function on my page. There are no errors, but the next function retrieveAllArticles() is not being executed.

    public saveAllArticles(article) {
    for(let data in article) {
      this.db.executeSql("INSERT INTO `all_articles` (id, titre, introduction, image, redacteur_nom, redacteur_twitter, date_publication, contenu_part1, tweet, image2, contenu_part2, tweet2, image3, contenu_part3, tweet3, image4, contenu_part4, tweet4, image5, contenu_part5, tweet5, image6, contenu_part6, tweet6, image7, contenu_part7, tweet7, image8, contenu_part8, tweet8, image9, contenu_part9, tweet9, image10, contenu_part10, tweet10) VALUES (" +
        article[data].article_id + ',"' +
        article[data].article_titre + "\")", {})
        .then(() => {
          console.log("Inserted");
        }).catch(e =>
        console.log("Error :" + JSON.stringify(e))
      );
    }
  }


  public retrieveAllArticles() {

    console.log("Retrieve");
    this.allArticles = [];
    this.db.executeSql('SELECT id FROM `all_articles`', {})
      .then((data) => {

      console.log(data);

      if(data == null) {
        return;
      }

      if(data.rows) {
        if(data.rows.length > 0) {
          for(let i = 0; i < data.rows.length; i++) {
            this.allArticles.push(data.rows.item(i).article_id);
          }
        }
      }
    });

    return this.allArticles;
  }

The console.log("Retrieve"); is not displayed, but the console.log('Inserted'); is displayed.

The constructor of my page :

    constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              protected articlesService: ArticlesService,
              protected sqliteService: SqliteService,
              private network: Network,
              public toastCtrl: ToastController,
              public platform: Platform)
  {
    this.observable$ = this.articlesService.getAllArticles();

    if (this.platform.is('cordova')) {
      sqliteService.createDatabaseFile();

      this.articlesService.getAllArticles().subscribe(article => {
        this.allArticles = article;
        this.sqliteService.saveAllArticles(this.allArticles);
      });

      this.allArticles = this.sqliteService.retrieveAllArticles();
    }
  }

After making some changes :

constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              protected articlesService: ArticlesService,
              protected sqliteService: SqliteService,
              private network: Network,
              public toastCtrl: ToastController,
              public platform: Platform)
  {
    this.observable$ = this.articlesService.getAllArticles();

    if (this.platform.is('cordova')) {
      sqliteService.createDatabaseFile();

      this.articlesService.getAllArticles().subscribe(article => {
        this.allArticles = article;
        this.sqliteService.saveAllArticles(this.allArticles);
        this.allArticles = this.sqliteService.retrieveAllArticles();
        console.log("articles");
        console.log(this.allArticles);
      });

    }
  }

https://i.sstatic.net/vBBcr.jpg

    public saveAllArticles(article) {

    let insertions: Array<Promise<any>> = [];
    console.log("insertions", insertions);
    for (let data in article) {
      insertions.push(this.db.executeSql("INSERT INTO `all_articles` (id, titre, introduction, image, redacteur_nom, redacteur_twitter, date_publication, contenu_part1, tweet, image2, contenu_part2, tweet2, image3, contenu_part3, tweet3, image4, contenu_part4, tweet4, image5, contenu_part5, tweet5, image6, contenu_part6, tweet6, image7, contenu_part7, tweet7, image8, contenu_part8, tweet8, image9, contenu_part9, tweet9, image10, contenu_part10, tweet10) VALUES (" +
        article[data].article_id + ',"' +
        article[data].article_titre + "\")", {}))
      Promise.all(insertions).then(() => {
        console.log("All records have been inserted");
        this.allArticles = this.retrieveAllArticles();
      }).catch(e => {
        console.log("Error :" + JSON.stringify(e))
      });
    }
  }

Can someone please assist me with this issue?

Thank you in advance

Answer №1

In order to ensure that you can access the data once all saving tasks are done, consider implementing the following solution:

public saveAllPosts(post) {
  // Create an array of promises
  let insertions: Array<Promise<any>> = [];
  for (let data of post) {
    insertions.push(this.db.executeSql("INSERT INTO ...", {}));
  }
  // Execute all promises and then retrieve all posts
  Promise.all(insertions).then(() => {
      console.log("All records have been inserted");
      this.allPosts = this.sqliteService.retrieveAllPosts();
    }).catch(e => {
      console.log("Error: " + JSON.stringify(e))
    });
}

The method of grouping promises is inspired by this response from Günter Zöchbauer.

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

The compilation of debug Java with Javac in CordovaLib is not being done incrementally

I am currently in the process of setting up Ionic on my new computer, but I have encountered an issue while trying to build a Cordova Android project that I can't seem to resolve. The software and versions I am using include: NodeJS v6.9.1 npm ...

How to create classes in typescript without utilizing the class keyword

As someone new to TypeScript, I have a curious question about classes. In pre-ES6 JavaScript, there were no classes. So, naturally, one would think it's possible to avoid using them in TypeScript as well. However, I am struggling to figure out the c ...

When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value. const arrayDays = Array.from(Array(32).keys(), (num) =& ...

Issues with the effectiveness of the clarity custom filter in Angular

I'm currently working on a datagrid table that contains a 'status' column. My goal is to create a custom filter that will provide users with a dropdown menu to select specific values. Additionally, I want the column to exclude two values, &a ...

Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset: roles = [ {roleId: "69801", role: "ADMIN"} {roleId: "69806", role: "SUPER_ADMIN"} {roleId: "69805", role: "RB"} {roleId: "69804", role: "PILOTE"} {roleId: "69808", role: "VENDEUR"} {roleId: "69807", role: "SUPER_RB"} ] The o ...

Angular seems to be experiencing issues with maintaining context when executing a function reference for a base class method

Imagine we have CtrlOne that extends CtrlTwo, with a componentOne instantiated in the template of CtrlOne. Here is some code to illustrate the issue: class CtrlOne extends CtrlTwo { constructor() { super(); } } class CtrlTwo { sayMyName(name: st ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Exploring a JSON object using PlaywrightWould you like to know how

Greetings! Here is a snippet of code that I have, which initiates an API call to a specific URL. const [response] = await Promise.all([ page.waitForResponse(res => res.status() ==200 && res.url() == & ...

Condition not applying in the Modal

I implemented *ngif on a button to show/hide it based on a condition, but it's not working as expected. The button should appear when an item is selected from ng-select. Here is the button code: <button *ngIf="switch" (click)="productSaveInCart() ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Issue: The last loader (./node_modules/awesome-typescript-loader/dist/entry.js) failed to provide a Buffer or String

This issue arises during the dockerhub build process in the dockerfile. Error: The final loader (./node_modules/awesome-typescript-loader/dist/entry.js) did not return a Buffer or String. I have explored various solutions online, but none of them have pr ...

Using Typescript with AWS Lambda can sometimes be a bit tricky. For example, when trying to invoke your Lambda function locally using "sam local invoke", you might encounter an error stating

Attempting to deploy an AWS Lambda function using the sam command with AWS's Hello World Example Typescript template, but encountering issues with the example template. Suspecting a bug within AWS causing this problem. This issue can be easily repli ...

Is it possible to select a tab in Angular 10 Material Tabs based on a route parameter?

My webpage features a mat-tab-group, located at the URL /transactions. <mat-tab-group> <mat-tab label="Shipments"> <ng-template matTabContent> shipment content </ng-template> ...

SQLite is unable to convert the Unicode buffer it returns into strings that can be effectively used

Currently, I'm retrieving records from a sqlite3 database. The data is stored as TEXT in the database, but when retrieved, it comes back as buffers in Unicode format that I can't seem to convert into readable text. To make it functional, I have ...

Enhancing the Look: A Guide to Angular Styling

As a newcomer to angular design and styling, I find myself facing a challenge in incorporating existing styles into my new project. My predecessor, who has since moved on from the project, had used certain styles that I need to adopt. Despite installing ui ...

Having trouble reading properties of undefined (specifically 'listen') during testing with Jest, Supertest, Express, Typescript

Issue: While running jest and supertest, I encounter an error before it even gets to the tests I have defined. The server works fine when using the start script, and the app is clearly defined. However, when running the test script, the app becomes undefi ...

Angular allows users to interact with objects in THREE.js by simply clicking on

I've tried numerous solutions, but none of them seem to work - the cube is in the wrong position and only one face is detected. Since the angular event is easy to call. 1. Insert a tag into the HTML code. <div (click)="onClickCanvas($event)"> ...

unfamiliar element detected in custom component

I recently created a simple component in Ionic as a test. I used the Ionic CLI to generate the component, and here is an excerpt from my app.module.ts file: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/p ...

What factors does mongo consider when serializing an object?

I recently started working with BigNumbers from the bignumber.js package As I delve into Mongo, I find myself pondering how Mongo manages to serialize objects correctly, such as the BigNumbers. In my case, I have encountered a puzzling situation where two ...

Angular CLI "serve" encountered a 404 status code when using CURL, yet the webpage is loading successfully in the browser

As I develop a new application using angular2 within Electron, I always aim to automate every aspect of the process. To achieve this, I have implemented various NPM scripts for serving, building, and packaging within the Electron wrapper. However, I am cur ...