How to compile a list with data from an Observable?

Asked

Viewed 651 times

1

How to go through data from an Observable and insert into a list?

I would like to compile a list of all the arrays within Observable that comes from Cloud Firestore, because I need a list of people to display in Mattabledatasource.

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

    export MyClass {
        list_pessoa: Pessoa[] = [];
        pessoa: Observable<Pessoa[]>;

        constructor(){

    // Algo parecido como isso, mas que funcione!
    this.pessoa.forEach(v =>{
      const d = v.values()
      this.list_pessoa.push(d);
    })

    console.log(this.list_pessoa);

}
}

Exit: list_person [ {'name': 'person1', 'city': 'city1'},
{''name': 'people2', 'city': 'city2'} ]


  • What is the best way to go through the data inside the Observable and insert into a list of arrays?

1 answer

0

You can make the iteration by signing up for the Observable response so:

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

export MyClass {
    list_pessoa: Pessoa[] = [];
    pessoa: Observable<Pessoa[]>;

    constructor(){

    this.pessoa
     .subscribe(res => this.list_pessoa = res);

    console.log(this.list_pessoa);
    }
}

Return method:

  getPessoas() {

    this.pessoasCol = this.afs.collection('pessoas', ref => ref.orderBy('nome', 'asc'));

    this.pessoas = this.pessoasCol.snapshotChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data() as Pessoa;
        data.id = a.payload.doc.id;
        return data;
      });
    });

    return this.pessoas;
  }

The method call is made as follows:

this.pessoa = this.providerPessoa.getPessoas();
  • Hello Arnaldo, I thank you from now on the intention to want to help but you are not returning anything from the Observable using subscribe, take a look above at the method that returns the Observable if necessary.

Browser other questions tagged

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