与Ionic 4的SQLite?无法读取未定义的属性'then'TypeError:无法读取未定义的属性'then'

时间:2018-09-25 19:28:33

标签: angular sqlite ionic-framework android-sqlite ionic4

首先我有this error,我解决了。好,很好。当我尝试使用设备进行调试时(使用ionic cordova run android)。数据库SQL未加载,它显示好像什么也没有创建数据库sqlite。我在控制台中签到,然后看到了:

  

ERROR错误:未捕获(承诺):TypeError:无法读取> undefined的属性'then'   TypeError:无法读取未定义的属性“ then”      在AppComponent.push ../ src / app / app.component.ts.AppComponent.createDatabase>(app.component.ts:101)      在app.component.ts:87

在app.component.ts中,我有这个:

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

在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({       名称:“ data.db”,       location:'default'//位置字段为必填     })。然后((db:SQLiteObject) <---我认为这是错误,但我不知道为什么。

我的信息:

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

有解决方案吗?作为记录,我是一个初学者,也许代码中有一些转义。

谢谢。

4 个答案:

答案 0 :(得分:0)

我在我的项目中正在使用它,并且可以正常工作。尝试看看是否有帮助。

import { Injectable } from '@angular/core';
import { SQLiteObject, SQLite } from '@ionic-native/sqlite';
import { Platform } from 'ionic-angular';

@Injectable()
export class SqliteHelperService {

  private db: SQLiteObject

  constructor(
    public platform: Platform,
    public sqlite: SQLite) {
  }

  
  private createDatabase(dbName?:string): Promise<SQLiteObject> {
    return this.platform.ready()
      .then((readySource: string) => {
        return this.sqlite.create({ 
          name: dbName || 'ks.db',
          location: 'default'
        }).then((db: SQLiteObject) => {
          this.db = db;
          return this.db;
        }).catch((error: Error) => {
          console.log('Error on open or create database: ', error);
          return Promise.reject(error.message || error);
        });  
      });  
  }

  getDb(dbName?:string, newOpen?:boolean): Promise<SQLiteObject>{
    if (newOpen) return this.createDatabase(dbName);
    return (this.db) ? Promise.resolve(this.db) : this.createDatabase(dbName);
  }  

}

答案 1 :(得分:0)

让我们稍微更改一下代码:

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

在这里,如果connundefined,那么您正试图致电undefined.then,这完全没有道理。这就是为什么您得到错误。真正的原因是它无法创建数据库连接。那是一个完全不同的问题。如果您按如下所示更改代码,将会更容易:

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

尽早发现错误可以使代码更容易调试。

答案 2 :(得分:0)

我也使用sqlite whit angular 6和ionic v4,我认为您返回数据库的所有对象的方式有些肮脏,您将在服务上执行数据库的所有交互并仅返回结果

import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';

@Injectable()
export class SQLiteService {

  constructor(
    private sqlite: SQLite
  ) {}

  rawQuery(queryText: string, params?: any[]): any {
    return new Promise((resolve, reject) => {
      this.sqlite.create({name: 'data.db', location: 'default'}).then((db: SQLiteObject) => {
        db.executeSql(queryText, params || []).then((data) => {
          resolve(data);
        }).catch(error => reject(error));
      }).catch(error => reject(error));
    });
  }
}

答案 3 :(得分:0)

ionic cordova platform add browser

然后

ionic cordova run browser

我必须运行第二个命令。对于第一个命令,因为它在我执行第一个命令后没有为我构建。在此之后,它起作用了。