How to use LoadingController + Angularfire 2 + Promise Request

Hi,

I wanted to use the LoadingController with Angularfire 2.

Current code sample

export class ItemPage {

items: FirebaseListObservable<any>;
loading: any;

constructor(public navCtrl: NavController, public navParams: NavParams, 
    public ngFire: AngularFire, public loadingCtrl: LoadingController) {

    this.loading = this.loadingCtrl.create({
        content: "Please wait...",
    });

    this.loading.present();
    this.getItems();
}

getItems() {
    this.ngFire.database.list('/items');
    this.loading.dismiss();
}

}

But the loading symbol doesn’t wait until the Firebase fetch the data. I understand, i have to use the Promise here. But don’t know how to use that.

Thanks

Something like this…

getItems() {
   this.ngFire.database.list('/items')
      .then((_data)=> {
            console.log('success')
            this.loading.dismiss();
            return _data;
      }).catch(err => {
            console.log(err, 'You do not have access!');
            this.loading.dismiss();
      });

}

@aaronksaunders

That didn’t worked. Got the following errors

Property ‘then’ does not exist on type ‘FirebaseListObservable<any[]>’.

what version of angular fire are you using…

Personally I don’t like storing loading controllers in object properties. It becomes unclear who is responsible for things when they are created in one place and torn down in another. Instead I prefer to always make them locally scoped, like so:

let loading = this._loadings.create({});
loading.present();

task().finally(() => {
  loading.dismiss();
}).subscribe((result) => {
  // do stuff with result
}, (err) => {
  // deal with error
});

its a good think you said personally :slight_smile: everyone has opinions…

I spent many years bashing my head against bugs in C/C++ where memory is allocated in one place and freed in another. It’s so easy to make memory leaks or hard-to-reproduce double dispose disasters under those conditions, and I think this is a (albeit fairly distant) cousin of that sort of situation.