2017-09-26 43 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