How to make a filter in an Observable?

0

How to make a filter on an Observable returned from the FireStore Cloud?

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 search field value, the Firebase return is an Observable, I would like to update personList by doing 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 like below, I would like to show only the people that have the name that I type in 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>
    
asked by anonymous 16.01.2018 / 15:57

1 answer

0

You want to filter the array and not the observable that envelopes the array . Therefore you must map using the map function.  the content of the observable (which is Pessoa[] ) and then rather 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;
            }
        }));
}
    
16.01.2018 / 16:26