Obtain data from sqlite Ionic 4

I have a problem with my code that when I go to look for the data that I have stored in sqlite these are executed at the end and I need them since these I need them to consume a service that will finally load the data on the screen. I leave my code below

 import { Component, OnInit } from '@angular/core';
 import { LoadingController, Platform } from '@ionic/angular';
 import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
 import { Uid } from '@ionic-native/uid/ngx';
 import { EsqueletoServiceProvider } from '../../providers/no4get- 
 service/no4get-services';
 import { DatabaseServiceProvider } from '../../providers/database- 
 service/database-service';
 import { AlertController } from '@ionic/angular';

 @Component({
   selector: 'app-general',
   templateUrl: './general.page.html',
   styleUrls: ['./general.page.scss'],
 })
 export class GeneralPage {
   listaCategorias: any;
   token: any;
   imei: string;
   cards: any;
   loading: any;
   datosTelefono: any;


   constructor(private loadingController: LoadingController,
     public esqueletoService: EsqueletoServiceProvider,
     public databaseService: DatabaseServiceProvider,
     public uid: Uid, 
     public androidPermissions: AndroidPermissions,
     public alertCtrl: AlertController,
     public platform: Platform
     ) 
   { 
     this.listaCategorias = "1";
     this.databaseService.getSesion(1).then(result => {
       this.token = result.valor;
     })
     .catch( error => {
       this.MostrarAlerta("Noticias","","Hubo un problema al obtener los 
       datos del usuario.");
     });

     this.databaseService.getSesion(2).then(result => {
       this.imei = result.valor;
     })
     .catch( error => {
       this.MostrarAlerta("Noticias","","Hubo un problema al obtener los 
       datos del usuario.");
     });
   }



 ionViewDidEnter()
   {
     this.platform.ready().then(() => { 
       let datos = { 
         idNoticias: 0, 
         token: this.token,
         imei: this.imei
       };

       this.LoaderNoticias();
       this.esqueletoService.CargarNoticiasGeneral(datos).then((result) => 
       {
         if (result != null) 
         {
           let codigoError = result.toString().split('|');

           if(codigoError[0] == "777")
           {
             this.loadingController.dismiss();
             this.cards = result;
           }
           else if (codigoError[0] == "305")
           {
             this.loadingController.dismiss();
             this.MostrarAlerta("Noticias","",codigoError[2]);
           }
           else if (codigoError[0] == "310")
           {
             this.loadingController.dismiss();
             this.MostrarAlerta("Noticias","",codigoError[2]);
           }
           else if(codigoError[0] == "315")
           {
             this.loadingController.dismiss();
             this.MostrarAlerta("Noticias","",codigoError[2]);
           }
           else if(codigoError[0] == "000")
           {
             this.loadingController.dismiss();
             this.MostrarAlerta("Noticias","","Estimado usuario, hubo un 
             error inesperado.");
           }   
         } else {
           this.loadingController.dismiss();
           this.MostrarAlerta("Noticias","","Estimado usuario, hubo un 
           error inesperado.");
         }
       }, (err) => {
         this.loadingController.dismiss();
         this.MostrarAlerta("Noticias","","Estimado usuario, hubo un error 
         inesperado.");
       });
     });
   }

Currently, when the ionViewDidEnter () event is executed, it creates a variable called data that is where I want to send an array to my service, but the token and imei fields up to that point are “undefined”. By following the path to the code once the entire ionViewDidEnter () event is executed, the code just allocates the data of the token and imei variables that are in the constructor. The question is, how can I get this data to be obtained before the ionViewDidEnter () event is executed?

my code is being executed in visual studio code and ionic 4. I thank you in advance for all the possible help you can give me, while I will continue investigating

I think the key here is that you seem to be trying to write in an imperative programming style, whereas Ionic apps are naturally reactive. The first thing I would do is to get all this junk out of the page, and invert the design. The page’s job seems to be presenting cards to the user. So what the page would love would be a function that gives it an array of cards:

class EsqueletoService {
  cards(id: number): Promise<Card[]> {
   ...
  }
}
class GeneralPage {
  cards: Card[] = [];
  constructor(private esqueletos: EsqueletoService) {}
  ionViewDidEnter(): void {
    this.esqueletos.cards(0)
      .then(cards => this.cards = cards);
      // either hang error handling off here, or deal with it in EsqueletoService
  }
}

Now the page is happy, and the problem becomes “how do we write EsqueletoService.cards given that it relies on other futures resolving?”.

class EsqueletoService {
  constructor(private db: DatabaseService) {
  }

  cards(id: number): Promise<Card[]> {
    return Promise.all(this.db.getSesion(1), this.db.getSesion(2))
      .then(dbstuff => {
        // this step effectively builds `datos` once all the necessary info is available
        return {token: dbstuff[0], imei: dbstuff[1], idNoticias: id};
      })
      .then(datos => this.cargarNoticiasGeneral(datos));
  }
}

There are some details omitted about how to actually turn the result from cargarNoticiasGeneral into an array of Card. That should all be done within cards, so the page doesn’t have to think about it.

1 Like