2017-09-26 70 views
0

在我的項目中,我使用的是Ionic 3和AngularFire2。我必須從firebase數據庫中獲取價值並做一些更改並將其顯示在HTML頁面中,以便我必須等待訂閱完成。這裏是我的代碼:如何使用地圖代替Angularfire2中的訂閱,Ionic 3

items: FirebaseListObservable<any[]>; 

constructor(public navCtrl: NavController, public afDB: AngularFireDatabase) {} 

async ionViewDidEnter(){ 

    var a = await this.calldatabase(); 
    console.log(a);  // it display first and value is undefined 
    console.log('3');  // it display second 
} 

async calldatabase(){ 

    let category: any; 
    this.items = this.afDB.list('/cat', { preserveSnapshot: true }); 
    await this.items.subscribe(snapshots => { 
    snapshots.forEach(snapshot => { 
     console.log(snapshot.val());  // it displays third 
     category = snapshot.val(); 
    }); 
    }); 
    return category; 
} 

`

我不能等待認購完成,然後我用Google搜索它,然後發現這些鏈接

angularfire2 wait for subscription to end?

Angular 2 Wait for subscription to complete

How to wait for a AngularFire2 subscription to finish before running the next lines of code Angular2

無法解決。現在,我試着去使用地圖,而不是認購不顯示任何

import 'rxjs/add/operator/map'; 

async calldatabase(){ 

    let category: any; 
    this.items = this.afDB.list('/cat', { preserveSnapshot: true }); 
    await this.items.map(snapshots => { 
    console.log(snapshots);    // it displays nothing 

    snapshots.forEach(snapshot => { 
     console.log(snapshot.val());  // it displays nothing 
     category = snapshot.val(); 
    }); 
    }); 
    return category; 
} 

My Cat value in database

回答

0
this.afDB.list('/cat', { preserveSnapshot: true }); 

這是可觀察到的,你可以訂閱上。

async calldatabase(){ 


    return this.afDB.list('/cat', { preserveSnapshot: true }); 

} 

然後,你需要的數據

showMyData(){ 

this.callDatabase.subscribe((data)=>{ 
//Do something with this data 
console.log(data)}); 

} 

我建議你使用火力地堡和服務爲貓的模型,你可以使用此語句中的組件。 的,你可以使用下面的代碼:

showMyData(){ 

let theCats: Cats[]; 

this.callDatabase.subscribe((data)=>{ 
theCats = data; 
console.log(theCats)}); 

//Do something with theCats 
} 
+0

我做到了,但它不工作 – LucidKit

+0

也許你可以張貼到現在爲止已代碼。 – hsc

相關問題