Help with events "IonViews" IONIC 2


#1

Why no execute(this.refresh) in event ionviewwillenter ?

ionViewWillEnter(){
this.refresh();
this.menu.enable(false);
}

public refresh() {
      return new Promise((resolve, reject) => {
      this.storage = new SQLite();
      this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {     
            this.storage.executeSql("SELECT * FROM configDB", [])
            .then(
              (data) => {            
                if(data.rows.length > 0){
                  this.token = data.rows.item(0)['token'];
                }                       
              }, 
              (error) => { 
                reject(error);
                this.database.presentToast("NĂŁo foi possĂ­vel carregar os dados da tabela: configDB" + error); 
            });
         },
          (error) => {
        this.database.presentToast("NĂŁo foi possĂ­vel abrir o banco de dados!" + error);
      });
      })
    }

#2

Could you please post the entire component you’re trying to achieve this in? Is it really necessary to call a refresh on this huge function? Isn’t it possible to do this once, then store it somewhere inside a service from which you can easily retrieve it afterwards? So if any alterations are made to the specific data, you should synchronously update the values inside the service as well as in your database.

Some more questions to be answered: does anything get’s triggered within the ionViewWillEnter? And are you doing this in a real page or inside a custom component?


#3

I’m not seeing a need for directly using SQLite here at all, which should probably make things much simpler.


#4
import { Component, ViewChild } from '@angular/core';
import { NavController, ToastController, MenuController } from 'ionic-angular';
import { SQLite } from 'ionic-native';
import { OrcamentoPage } from '../orcamento/orcamento';
import { ConfigPage } from '../config/config';
import { LoginInterface} from '../../interfaces/interface';
import { Webservice } from '../../providers/webservice';
import { Database } from '../../providers/database';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public toast: any;
  public login:any;
  focus: string = '';
  public versao: any = "20170331";
  public token: any;
  public loginhome: LoginInterface = {usuario:'',senha:''};
  private storage: SQLite;
  @ViewChild('inputusuario') inputUsuario;
  @ViewChild('inputsenha') inputSenha;

  constructor(public nav: NavController, public webservice: Webservice, public toastCtrl: ToastController, public database: Database, public menu: MenuController) {
    this.menu.enable(false);
  }

  ionViewDidEnter(){
    this.database.limpaCarrinho()
    .then((data) => {
      return this.webservice.buscaServidor()
      .then((data) => {
        console.log("ok");         
      });
    }, (error) => {
      this.database.presentToast(error);
    })
    this.refresh();
    this.menu.enable(false);
  }

  ionViewDidLeave() {
    this.menu.enable(true);
  }

  public nextPage(page: any, data: any){
    if( data == "#logadoComSucessoOK#"){
      this.database.insereUsuario(this.login.usuario)
      .then((data) => {
        this.nav.setRoot(page);
        this.database.dismissLoadingDefault();
      }, (error) => {
        console.log(error);
      })
    }else{
      this.database.presentToast(data);
      this.database.dismissLoadingDefault();
      setTimeout(() => {
        this.inputSenha.setFocus();
      },1000);
    }
  }

  public logar(){
    this.login = this.loginhome;
    if(this.login.usuario == ""){
      this.inputUsuario.setFocus();
      return 0;
    }
    if(this.login.senha == ""){
      this.inputSenha.setFocus();
      return 0;
    }

    this.database.presentLoadingDefault();
    this.webservice.login(this.login, this.versao, this.login.usuario, this.token)
    .then(
      (data)=> {
        this.nextPage(OrcamentoPage, data);
      })
    .catch(
      (ex) => {
        this.database.dismissLoadingDefault();
        this.database.presentToast("Erro no servidor: " + ex);
    });  
  }
  
  public refresh() {
      return new Promise((resolve, reject) => {
      this.storage = new SQLite();
      this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {     
            this.storage.executeSql("SELECT * FROM configDB", [])
            .then(
              (data) => {            
                this.token = data.rows.item(0)['token'];
                resolve(data);                      
              }, 
              (error) => { 
                reject(error);
                this.database.presentToast("NĂŁo foi possĂ­vel carregar os dados da tabela: configDB" + error); 
            });
         },
          (error) => {
        this.database.presentToast("NĂŁo foi possĂ­vel abrir o banco de dados!" + error);
      });
      })
    }

  public openConfig(){
    this.nav.setRoot(ConfigPage);
  }
  
}

#5

if i do: ionViewWillEnter(){
this.refresh();
}

and i go to other page and back to homepage it’s work…


#6

Okay, what about the other questions asked? Does anything run within your ionViewWillEnter() (which isn’t in your component atm, but I guess you know that :joy:)? And what’s with those any types? It’s one of the first things you should get rid off because it makes debugging your components a lot easier and therefore it will save you time in the end. Plus your project is better to maintain for other developers in the future as well (could give you some more reasons).

Also as @rapropos said, is it really necessary to put this stuff in a SQlite db? Why not use ionic storage?


#7

What is the problem with using sqlite?


#8

i need save all configurations in sqlite…
and load when needed


#9

I didn’t say there was a problem, I did say I think it’s an absolute overkill to use sqLite for what you’re using it for in this particular component. Ionic storage provides easy getters and setters and can decide for you what’s te best storage to use on a particular device. But if you want to use sqLite I won’t tell you you can’t off course :slight_smile:

Regarding your question, does anything run at all inside your ionViewWillEnter?


#10

It’s more complicated to deal with directly than ionic-storage is, and the way you’re doing it is even more so (you’re bypassing ionic-native and instantiating needless matryoshka Promises). It also isn’t usable in browsers, whereas ionic-storage is.


#11
ionViewDidEnter(){
    this.database.limpaCarrinho() WORK
    .then((data) => {
      return this.webservice.buscaServidor() WORK
      .then((data) => {
        console.log("ok");         
      });
    }, (error) => {
      this.database.presentToast(JSON.stringify(error));
    })
    this.refresh(); NOT WORK
    this.menu.enable(false); WORK
  }

#12

Wow nice, My company wants to use sqlite, but will the problem be related to db?


#13

When you are running on device, ionic-storage will use sqlite under the hood. You just won’t have access to SQL, everything is a key/value pair. That’s typically fine for most applications, including what you’ve described here.


#14

You should convince them with some decent arguments then :wink: But regarding your question, does this.refresh() works at all? If you put a breakpoint in the beginning of the function, isn’t triggered at all or does it just not execute what you expect it should execute?


#15

When I compile the application this.refresh works … but when I close the application and open again it does not work, only if I close it to get out of the “memory”


#16

I discovered the problem: If I close the app with this.platform.exitApp (); And I re-open it again the ionviewdidenter does not work anymore. It only works again if I take the application from the app list in the background. How to solve it now ?


#17

I suspect the fundamental problem is a race condition whereby attempts are made to access the database before it is ready. Please refactor your app to use ionic-storage instead of sqlite directly, wait on its ready promise properly, and see if your problem goes away.