0

In my project, I am using Ionic 3 and AngularFire2. I have to get the value from firebase database and to do some changes and display it in HTML page so that I have to wait for subscription to complete. Here is my code:

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;
}

`

I can't make wait for subscription to complete, then I googled it and then found these links

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

Can't able to resolve. Now Im trying to use map instead of subscription it doesn't display anything

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

LucidKit
  • 28
  • 5

1 Answers1

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

This is an Observable where you can Subscribe on.

async calldatabase(){


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

 }

Then you can use this statement in the component where you need the data

showMyData(){

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

}

I suggest that you use a service for Firebase and a model for the Cat. The you can use the following code:

showMyData(){

let theCats: Cats[];

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

//Do something with theCats
}
Hans
  • 523
  • 1
  • 5
  • 16