Search code examples
angularfirebasegoogle-cloud-firestoreangularfire2

Angular 6 firebase get list from cloud firestore


i want to know how to get lists from cloud firestore.

I upload list like this :

export interface Data {
  name: string;
  address: string;
  address2: string;
  pscode: string;
  ccode: string;
  name2: string;
}

constructor(private afs: AngularFirestore){
    this.notesCollection = this.afs.collection(`imones`, (ref) => ref.orderBy('time', 'desc').limit(5));
}

  notesCollection: AngularFirestoreCollection<Data>;

//creating item in list (imones)

createItem(){
  this.notesCollection.add(this.busines);
}

Now the question is how to get all list items from there ?

That's my try :

constructor(private afs: AngularFirestore){
  this.items = this.notesCollection.valueChanges();
}
  items: Observable<Data[]>;

HTML :

 <p *ngFor="let item of items">{{item.name}}</p>

ERROR:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Again error :

enter image description here


Solution

  • You are trying to iterate over an observable. the *ngFor loop allows you to iterate only on iterables (arrays, sets)

    You have 2 options:

    1. Use the built-in async pipe in order to iterate over an observable. e.g:

      <p *ngFor="let item of items | async">{{item.name}}</p>

    2. Subscribe to the observable and update a variable with the latest result from it (the observable result in your case is an array):

      this.notesCollection.valueChanges()
                          .subscribe((items) => this.items = items);