How to filter an Observable?

Asked

Viewed 636 times

0

How to filter a Observable returned from Cloud Firestore?

export interface Pessoa {
   nome: string;
   cidade: string;
   telefone: string;
}

pessoaList: Observable<Pessoa[]>;

I have the method below that is called every time I update the value of the search field, the return of Firebase is an Observable, I would like to update personal Leader making a filter with the name of the person I want to display on the screen.

getItems(searchbar){
    var q = searchbar.srcElement.value;

    if (!q) {
      return;
    }

    // Isto aqui não funciona!!!
    this.pessoaList = this.pessoaList.filter((v) => {
      if(v.nome && q) {
        if (v.nome.toLowerCase().indexOf(q.toLowerCase()) > -1) {
          return true;
        }
        return false;
      }
    });

    console.log(q, this.pessoaList.length);
}

In my HTML I have something similar to below, I would like to show only people who are with the name I type in the Searchbar.

    <ion-searchbar [(ngModel)]="myInput" 
    [showCancelButton]="shouldShowCancel" (ionInput)="getItems($event)" 
    (ionCancel)="onCancel($event)">
    </ion-searchbar>

<ul *ngFor="let p of pessoaList| async">
<li> {{p.nome }} </li>
</ul>

1 answer

0


You want to filter the array and not the observable which envelopes the array. So you should map using the function map the content of observable (which is Pessoa[]) and then yes filter it.

getItems(searchbar){
    var q = searchbar.srcElement.value;

    if (!q) {
      return;
    }    

    this.pessoaList = this.pessoaList
        .map(pessoaList => pessoaList.filter((v) => {
            if (v.nome && q) {
                return v.nome.toLowerCase().indexOf(q.toLowerCase()) !== -1;
            }
        }));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.