angularfiredatabase

Retrieving data as lists

AngularFire synchronizes data as lists using the AngularFireList service.
The AngularFireList service is not created by itself, but through the AngularFireDatabase service.
The guide below demonstrates how to retrieve, save, and remove data as lists.Injecting the AngularFireDatabase service
Make sure you have bootstrapped your application for AngularFire. See the Installation guide for bootstrap setup.
AngularFireDatabase is a service which can be injected through the constructor of your Angular component or @Injectable() service. In the previous step, we modified the /src/app/app.component.ts to retrieve data as an object. In this step, let's start with a clean slate.
Replace your /src/app/app.component.ts from previous step to look like below.
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  constructor(db: AngularFireDatabase) { }
}
In this section, we're going to modify the /src/app/app.component.ts to retrieve data as list, but before that let's look at ways around how to bind to a list.

Create a list binding

Data is retrieved through the AngularFireDatabase service. The service is also generic. Provide the singular type and not the array type.
const listRef = db.list('items');
const shirtsRef = db.list<Shirt>('shirts');

Retrieve data

To get the list in realtime, create a list binding as a property of your component or service.
Then in your template, you can use the async pipe to unwrap the binding.
Update /src/app/app.component.ts to import AngularFireList from @angular/fire and iterate through the list once data is retrieved. Also note the change in attribute templateUrl to inline template below.
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <ul>
    <li *ngFor="let item of items | async">
       {{ item | json }}
    </li>
  </ul>
  `,
})
export class AppComponent {
  items: Observable<any[]>;
  constructor(db: AngularFireDatabase) {
    this.items = db.list('items').valueChanges();
  }
}
Read More!

Comments