Olivier P
Olivier P

Reputation: 973

AngularFire2 check if a list is empty while subscribing

I use AngularFire2 with an Ionic2 app. I'm trying to load a list of elements from the database and display a spinner while it's loading.

I face an issue when the list is empty, I don't know how to inform the controller to stop the spinner because no data will ever come before a new add. I might not have the right structure.

So this is an extract of my service :

this.userTourList = this.af.database.list('/userProfiles/' + this.userId + '/tours/');
this.userTourList.subscribe((response) => {
    response.map((tourData) => {
        //Create and fill a TourSnapshot component
        let tourSnap = new TourSnapshot(tourData.name, tourData.$key);
        tourSnap.description = tourData.description;
        //[..]
        this.tours.push(tourSnap);
        //Return an array through my own observable
        return this.toursObservable.next(this.tours);
    });
}

This is my controller :

let loader = this.loadingCtrl.create({
    content: "Loading tours..."
});
loader.present().then(() => {
   //The list will be updated automatically
   tourData.getExpertTourList().subscribe(tourList => {
      this.tourList = tourList;
      loader.dismiss().catch(() => {});
   });
});

If the list is empty, my loader will never get dismissed (until a new add is done). I thought about using the isEmpty() method on the observable in my service like this :

this.userTourList.isEmpty().subscribe(isEmpty => {
//Force a return if the "tours" node is empty to indicate to the controller
//that nothing else will be returned before a new add
    if (isEmpty) {
       return this.userToursObservable.next(this.tours);
    }
});

But I always get a false value for isEmpty. How could I check if my list is empty without doing an extra call to the database ? (If it's possible).

Thank you

Upvotes: 2

Views: 1875

Answers (1)

Olivier P
Olivier P

Reputation: 973

Based on @cartant comment, I added a check on the size of the list before calling the map() method.

this.userTourList = this.af.database.list('/userProfiles/' + this.userId + '/tours/');
this.userTourList.subscribe((response) => {
    if (response.length == 0) {
       //Return an empty array anyway
       return this.toursObservable.next(this.tours);
    }
    response.map((tourData) => {
        //Create and fill a TourSnapshot component
        let tourSnap = new TourSnapshot(tourData.name, tourData.$key);
        tourSnap.description = tourData.description;
        //[..]
        this.tours.push(tourSnap);
        //Return an array through my own observable
        return this.toursObservable.next(this.tours);
    });
}

Upvotes: 1

Related Questions