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);
      });

    }
  }

    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 text inside the Mapbox GL popup cannot be highlighted or copied

I'm encountering an issue where the text in my popups is unselectable. Even though I can close the popups through various methods, such as clicking on them, the pointer remains as a hand icon when hovering over the text and doesn't change to the ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

minimize the size of the indigenous foundation input field

Currently incorporating this code snippet into my application: <Item fixedLabel> <Input style={{ width: 0.5 }}/> </Item> The fixedLabel element is extending the entire width of the screen. I have attempted adju ...

Finding the imported function in Jest Enzyme's mount() seems impossible

I'm currently facing an issue where I need to mount a component that utilizes a function from a library. This particular function is utilized within the componentDidMount lifecycle method. Here's a simplified version of what my code looks like: ...

Tips for using a TypeScript method decorator while maintaining the expected `this` scope

It was brought to my attention that the issue I encountered was due to the use of GraphQL resolvers in running my decorated method. This resulted in the scope of this being undefined. Nevertheless, the core of the question provides valuable insights for an ...

The Express API controller is unexpectedly receiving empty strings

I am encountering an issue where my API is receiving an empty string instead of the expected data when I send post requests with a single string in the body. Below are the client, server, and controller components involved: Function call (client): const ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

It seems that Ionic 2 does not support the registration of custom HTML tags

Encountering a problem with Ionic 2 and custom components. Developed a component to show in a list, serving as the list item. However, my app crashes when attempting to use the custom HTML tag. The stack trace is provided below. Uncertain about the issue. ...

Variables for Angular Material themes

My app has multiple theme files, and I select the theme during runtime. .client1-theme{ // @include angular-material-theme($client1-theme); @include all-component-colors($client1-theme); @include theme-color-grabber($client1-theme, $client1-a ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Unclear error message when implementing union types in TypeScript

Currently, I am attempting to define a union type for a value in Firestore: interface StringValue { stringValue: string; } interface BooleanValue { booleanValue: boolean; } type ValueType = StringValue | BooleanValue; var value: ValueType = { bo ...

What is the best way to navigate back to the previous page while retaining parameters?

Is there a way to return to the previous page with specific parameters in mind? Any suggestions on how to achieve this? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } What I am looking ...

Creating a default option of "please select" on an Angular select element with a null value for validation

Within my Angular application, I am using a select element with an ngFor loop: <select formControlName="type" required> <option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option> </select> When view ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

I'm looking to inject both default static values and dynamic values into React's useForm hook. But I'm running into a TypeScript type error

Below is the useForm code I am using: const { register, handleSubmit, formState: { errors, isSubmitting }, reset, getValues, } = useForm({ defaultValues: { celebUid, //props fanUid, // props price, // props ...

Firebase - Accessing data for a specific item

Apologies for the lengthy question. I have a collection of events that I retrieve like this: export class HomePageComponent implements OnInit { events: FirebaseListObservable<EventModel[]>; constructor( private authService: AuthService, ...

Mastering the art of passing and translating languages through selected options in different components using ngx-translate

Currently, I am utilizing the ngx-translate library for localization within a specific component and it is functioning correctly. Here's the setup: I have designed a language selection dropdown component that is being used in the Login component witho ...

Having trouble successfully deploying the app generated by "dotnet new angular" onto Azure

After creating an app using the dotnet new angular template and running dotnet run, everything seemed to be working smoothly. However, when I pushed the code to GitHub and set up continuous deployment in Azure, the build process failed. I turned on Devel ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...