必须在组件中使用 Device.ready,在 RC5 中使用服务



从 Beta.11 更新到 RC.2.0.5 后,我必须在使用使用 platform.ready() 的服务的组件中使用 platform.ready()。我有以下实现:

import { Component, Injectable } from '@angular/core';
import { SQLite } from 'ionic-native';
import { NavController, Platform } from 'ionic-angular';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class PageService {
  db: any;
  createUsageString = 'CREATE TABLE IF NOT EXISTS Usage (id INTEGER PRIMARY KEY AUTOINCREMENT, kWh NUMBER)';
  constructor(private platform: Platform) {
    platform.ready().then(() => {
      console.log('ready');
      console.log(SQLite);
      this.db = new SQLite();
      console.log(this.db);
      this.db.openDatabase({
        name: 'usage.db',
        location: 'default' // the location field is required
      }).then(() => {
        this.db.transaction((tx) => {
          tx.executeSql(this.createUsageString);
        }).then(() => {
          console.log('tables created');
          }).subscribe(data=>{
            console.log('this is the data',data);
          })
        }).catch((err) => {
          console.log('tables already created', err);
        });
      }).catch((err) => {
        console.log('Couldn't open database: ', err);
      })
    })
  }

如果我在这样的页面中使用服务:

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1 {
  constructor(public navCtrl: NavController,private pageService:PageService) {
  }
  ngOnInit(){
    console.log('console from with page component', this.pageService.db);
  }
}

this.pageService.db 返回未定义,但如果我将其包装在 platform.ready() 中,则已定义 this.pageService.db。见下文:

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1 {
  constructor(public navCtrl: NavController,private pageService:PageService, private platform: Platform) {
  }
  ngOnInit(){
    this.platform.ready().then(()=>{
    console.log('console from with page component', this.pageService.db);
    })
  }
}

从现在开始,我必须这样使用在我的组件中使用本机插件的服务吗?

我会做得稍微不同一些。从某种意义上说,与其在服务的构造函数中初始化数据库,我会编写一个这样的函数:

getDbInstance(){
    return new Promise((resolve, reject){
          this.platform.ready().then(() => {
              SQLite.openDatabase({
               name: 'usage.db',
               location: 'default' // the location field is required
               })
               .then(db=>{
                   return resolve(db);//Return db instance after loading
               })
               .catch(err=>{
                   return reject("error initialising DB")
               })
    })
}

在组件的构造函数中:

this.pageService.getDbInstance()
    .then(db=>{
        //using this db instance perform your transactions here
    })
    .catch(err=>{
        console.log("Error initialising DB")
    })

相关内容

  • 没有找到相关文章

最新更新