Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite with Ionic 4? Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined

First I had this error and I solved it. Ok, great. When I try to debug with my device (with ionic cordova run android). The database SQL does not loaded, it shows like has nothing or never was create the database sqlite. I check in the console and I see this:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'then' of >undefined TypeError: Cannot read property 'then' of undefined at AppComponent.push../src/app/app.component.ts.AppComponent.createDatabase >(app.component.ts:101) at app.component.ts:87

In app.component.ts I have this:

import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
import { DbService } from './services/db/db.service';


rootPage: string = null;
constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private translate: TranslateService,
    private router: Router,
    private menuCtrl: MenuController,
    public DbService: DbService,
    public sqlite: SQLite
    //private screenOrientation: ScreenOrientation
  ) {
    this.initializeApp();
  }

  public TableCreated = "POR EL MOMENTO NO";
  public ahora = "ahora";

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.translate.setDefaultLang('en');
      this.createDatabase();

    });
  }

  closeMenu() {
    this.menuCtrl.close();
  }

  private createDatabase(){
    this.sqlite.create({
      name: 'data.db',
      location: 'default' // the location field is required
    }).then((db: SQLiteObject) => {  <<<<----- ERROR HERE !!! but I don't know why.
      this.TableCreated = "FUE CREADA LA DB!";
      this.DbService.setDatabase(db);
      return this.DbService.createTable();
    })
    .then(() => {
      this.TableCreated = "FUE CREADA LA TABLA!";
      return this.DbService.createFirstRunningApp();
    })
    .then(() =>{
      this.TableCreated = "SE INSERTÓ LOS DATOS";
      this.splashScreen.hide();
      this.rootPage = 'HomePage';
    })
    .catch(error =>{
      console.error(error);
    });
  }

In db.services.ts:

import { SQLiteObject } from '@ionic-native/sqlite/ngx';


export class DbService {
db: SQLiteObject = null;

  constructor() { }

 setDatabase(db: SQLiteObject){
    if(this.db === null){
      this.db = db;
    }
  }

  createTable(){
    let sql = 'CREATE TABLE IF NOT EXISTS datis(id INTEGER PRIMARY KEY AUTOINCREMENT, dati TEXT, isTrue INTEGER DEFAULT 0, dateCreated datetime default CURRENT_TIMESTAMP)';
    return this.db.executeSql(sql, []);

  }

  createFirstRunningApp(){ //solo la primera vez se corre
    let allDate = [
      'Blablabla',
      'Something',
      'YellowBlueRed',
    ];
    let sql = 'INSERT INTO datis(dati) VALUES(?)';
    for (let dati of allDate) {
      this.db.executeSql(sql, [dati]);
    }
  }
}

this.sqlite.create({ name: 'data.db', location: 'default' // the location field is required }).then((db: SQLiteObject) <--- I think this is the error, but I don't know why.

My info:

Ionic:

   ionic (Ionic CLI)          : 4.1.2 (C:\Users\Tomas\AppData\Roaming\npm\node_m
odules\ionic)
   Ionic Framework            : @ionic/angular 4.0.0-beta.7
   @angular-devkit/core       : 0.7.5
   @angular-devkit/schematics : 0.7.5
   @angular/cli               : 6.1.5
   @ionic/ng-toolkit          : 1.0.8
   @ionic/schematics-angular  : 1.0.6

Cordova:

   cordova (Cordova CLI) : 8.0.0
   Cordova Platforms     : android 7.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-i
onic-webview 2.1.4, (and 4 other plugins)

System:

   NodeJS : v8.12.0 (C:\Program Files\nodejs\node.exe)
   npm    : 6.4.1
   OS     : Windows 7

Any solution? For the record, I'm a beginner, maybe there's something escaping in the code.

Thanks.

like image 702
Tomas Avatar asked Sep 25 '18 19:09

Tomas


2 Answers

ionic cordova platform add browser

and then

ionic cordova run browser

I had to run the 2nd command. With the first command, As it didn't build for me after first command. After this, it worked.

like image 73
karan bhatia Avatar answered Nov 20 '22 11:11

karan bhatia


Lets change your code slightly:

private createDatabase(){
  const conn = this.sqlite.create({
    name: 'data.db',
    location: 'default' // the location field is required
  })
  console.log('i think the db conn is undefined', conn);
  conn.then(() => {
    // etc
  })
}

Here, if conn is undefined then you are trying to call undefined.then which makes absolutely no sense. That's why you are getting the error. The real cause is that it is failing to create your db connection. That's a whole different problem. It would be easier if you changed your code as follows:

private createDatabase(){
  const conn = this.sqlite.create({
    name: 'data.db',
    location: 'default' // the location field is required
  })
  if (conn == null) throw Error('Failed to create database connection')
  conn.then(() => {
    // etc
  })
}

This catching of errors early makes code much easier to debug.

like image 35
danday74 Avatar answered Nov 20 '22 10:11

danday74