Ionic App:SQLite不能在模拟器中工作

时间:2017-10-31 18:04:33

标签: android sqlite cordova ionic-framework hybrid-mobile-app

您好我正在尝试按照有关在离子应用中实现sqlite的教程:https://www.youtube.com/watch?v=E6h8PFHMLIU

我在turoial中提出了所有建议,但是当我在android模拟器中运行应用程序时(离子cordova构建android;离子cordova运行android)它不会像在视频中那样显示数据库中的数据。我究竟做错了什么?您可以在下面看到代码

app.module.ts

  import { BrowserModule } from '@angular/platform-browser';
  import { ErrorHandler, NgModule } from '@angular/core';
  import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
  import { SplashScreen } from '@ionic-native/splash-screen';
  import { StatusBar } from '@ionic-native/status-bar';

  import { MyApp } from './app.component';
  import { HomePage } from '../pages/home/home';

  import { IonicStorageModule } from '@ionic/storage';
  import { HttpModule } from '@angular/http';

  import { DatabaseProvider } from '../providers/database/database';

  import { SQLitePorter } from '@ionic-native/sqlite-porter';
  import { SQLite } from '@ionic-native/sqlite';

  @NgModule({
    declarations: [
      MyApp,
      HomePage
    ],
    imports: [
      BrowserModule,
      HttpModule,
      IonicStorageModule.forRoot(),
      IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
      MyApp,
      HomePage
    ],
    providers: [
      StatusBar,
      SplashScreen,
      {provide: ErrorHandler, useClass: IonicErrorHandler},
      DatabaseProvider,
      SQLitePorter,
      SQLite
    ]
  })
  export class AppModule {}

database.ts

import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { SQLitePorter } from '@ionic-native/sqlite-porter';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { BehaviorSubject } from 'rxjs/Rx';
import { Storage } from '@ionic/storage';

@Injectable()
export class DatabaseProvider {
  database: SQLiteObject;
  private databaseReady: BehaviorSubject<boolean>;

  constructor(public sqlitePorter: SQLitePorter, private storage: Storage, private sqlite: SQLite, private platform: Platform, private http: Http) {
    this.databaseReady = new BehaviorSubject(false);
    this.platform.ready().then(() => {
      this.sqlite.create({
        name: 'developers.db',
        location: 'default'
      })
        .then((db: SQLiteObject) => {
          this.database = db;
          this.storage.get('database_filled').then(val => {
            if (val) {
              this.databaseReady.next(true);
            } else {
              this.fillDatabase();
            }
          });
        });
    });
  }

  fillDatabase() {
    this.http.get('assets/dummyDump.sql')
      .map(res => res.text())
      .subscribe(sql => {
        this.sqlitePorter.importSqlToDb(this.database, sql)
          .then(data => {
            this.databaseReady.next(true);
            this.storage.set('database_filled', true);
          })
          .catch(e => console.error(e));
      });
  }

  addDeveloper(name, skill, years) {
    let data = [name, skill, years]
    return this.database.executeSql("INSERT INTO developer (name, skill, yearsOfExperience) VALUES (?, ?, ?)", data).then(data => {
      return data;
    }, err => {
      console.log('Error: ', err);
      return err;
    });
  }

  getAllDevelopers() {
    return this.database.executeSql("SELECT * FROM developer", []).then((data) => {
      let developers = [];
      if (data.rows.length > 0) {
        for (var i = 0; i < data.rows.length; i++) {
          developers.push({ name: data.rows.item(i).name, skill: data.rows.item(i).skill, yearsOfExperience: data.rows.item(i).yearsOfExperience });
        }
      }
      return developers;
    }, err => {
      console.log('Error: ', err);
      return [];
    });
  }

  getDatabaseState() {
    return this.databaseReady.asObservable();
  }

}

home.ts

import { DatabaseProvider } from './../../providers/database/database';
import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  developer = {};
  developers = [];

  constructor(public navCtrl: NavController, private databaseprovider: DatabaseProvider, private platform: Platform) {
    this.databaseprovider.getDatabaseState().subscribe(rdy => {
      if (rdy) {
        this.loadDeveloperData();
      }
    })
  }

  loadDeveloperData() {
    this.databaseprovider.getAllDevelopers().then(data => {
      this.developers = data;
    })
  }

  addDeveloper() {
    this.databaseprovider.addDeveloper(this.developer['name'], this.developer['skill'], parseInt(this.developer['yearsOfExperience']))
      .then(data => {
        this.loadDeveloperData();
      });
    this.developer = {};
  }

}

home.html的

<ion-header>
  <ion-navbar>
    <ion-title>
      Developer Data
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label stacked>What's your name?</ion-label>
    <ion-input [(ngModel)]="developer.name" placeholder="Developer Name"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>What's your special skill?</ion-label>
    <ion-input [(ngModel)]="developer.skill" placeholder="Special Skill"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>How long have you been working?</ion-label>
    <ion-input [(ngModel)]="developer.yearsOfExperience" placeholder="Years of experience"></ion-input>
  </ion-item>
  <button ion-button full (click)="addDeveloper()">Add Developer Info</button>

  <ion-list>
    <ion-item *ngFor="let dev of developers">
      <h2>{{ dev.name }}</h2>
      <p>{{ dev.yearsOfExperience }} years of {{ dev.skill }} Experience!</p>
    </ion-item>
  </ion-list>
</ion-content>

0 个答案:

没有答案