2017-01-17 17 views
0

從Beta.11更新到RC.2.0.5後,我必須在組件內部使用platform.ready(),該組件使用的是使用platform.ready )。我有以下實現:必須使用RC5中的組件和服務中的Device.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

我會做得有點不同。在這個意義上,而是在初始化服務的構造函數的分貝,我會寫一個函數,像這樣:

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") 
    }) 
+0

看起來不錯。我會試試這個。 – inspired

相關問題