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

时间:2017-01-17 19:41:24

标签: ionic2

从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返回undefined,但如果我将它包装在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);
    })
  }
}

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

1 个答案:

答案 0 :(得分:1)

我会以不同的方式做到这一点。从某种意义上说,我不是在Service的构造函数中初始化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")
               })
    })
}

在Component的构造函数中:

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