Skip to content
Advertisement

Angular: conditionally render based on whether value was received from Firebase DB

I have a component:

export class MainpageComponent implements OnInit {

  items: Observable<any[]>;
  displayElement = false; //whether we will display the elemet or display a loading thing

  constructor(db: AngularFireDatabase) {
    this.items = db.list('questions').valueChanges();
  }
}

I am currently displaying the data I receive inside a swiper in the HTML template with no problems:

<swiper>
<ng-template swiperSlide *ngFor="let item of items | async">
    <div>
        <h2> {{ item.prop1 }} </h2>
        <h5> {{ item.prop2}} </h5>
    </div>
</ng-template>
</swiper>       

However, I now want to display the part above only after items have been loaded. And display something else (a loading indicator) while it loads. So I am planning something like this:

<div *ngIf="displayElement; else elseBlock">Items are not here yet</div>
<ng-template #elseBlock>

<!---- old code ------>
<swiper>
<ng-template swiperSlide *ngFor="let item of items | async">
    <div>
        <h2> {{ item.prop1 }} </h2>
        <h5> {{ item.prop2}} </h5>
    </div>
</ng-template>
</swiper>   
<! --------------->

</ng-template>

My only problem is that I don’t know how to update the displayElement variable value when items have been loaded from the firebase db (see first code block). I tried doing a .then(()={}) but valueChanges() does not return a promise.

Many thanks for any help.

Advertisement

Answer

valueChanges() is of type Observable, an Observable is a stream of events or data. To get the data from the database, you need to subscribe to the Observable. Therefore you have to use the subscribe() function:

db.list('questions').valueChanges().subscribe((res) =>{
    console.log(res);
    this.displayElement = true;
 },error => {
    console.log(error);
 },() => {
    console.log("completed");
});

The subscribe function takes 3 callbacks, the first one will be called whenever the Observable emits an item. Therefore you can change the value of displayElement after getting the first item from the database.

For reference:

http://reactivex.io/documentation/operators/subscribe.html

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement