View in ngModel Firestore return

Asked

Viewed 85 times

0

How to view data returned from the Firestore in an Angular ngModel directive?

I would like to take the data that is returned from the Firestore and display in an Angular ngModel directive, displaying on an edit screen.

pessoa.modelts.:

export class Pessoa {
    nome: string;
    telefone: string;
}

personal.service.ts

import { Injectable } from '@angular/core';

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Pessoa } from 'app/models/pessoa';

@Injectable()
export class PessoaService {

  pessoaDoc: AngularFirestoreDocument<any>;
  pessoasCursor: AngularFirestoreCollection<Pessoa>;

  constructor(private afs: AngularFirestore) {
    this.pessoasCursor = this.afs.collection('pessoas', ref => ref.orderBy('nome', 'asc'));
  }

  getValues(id?) {
    return this.pessoasCursor.valueChanges();
  }

view person.ts:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { Pessoa} from 'app/models/pessoa';
import { PessoaService } from 'app/services/pessoa.service';

@Component({
  selector: 'app-pessoa-edit',
  templateUrl: './pessoa-edit.component.html'
})
export class PessoaEditComponent implements OnInit {
  pessoaId: any;
  pessoa: any; // [(ngModel)]="pessoa.nome"

  constructor(private route: Router, private routeAct: ActivatedRoute,
  private pacienteService: PacienteService) { }

  ngOnInit() {
    this.routeAct.params.subscribe(params =>{
      this.pessoaId = params['id'];
    })

    // Retornar aqui apenas a pessoa com o ID
    this.pessoa = this.pessoaService.getValues(id);
  }

}

person-Edit.component.html:

<--! Aqui preciso exibir o nome que retornou do FireStore.-->

   <input type="text" [(ngModel)]="nome" formControlName="nome" name="nome" class="form-control" placeholder="Nome completo">

1 answer

0

I believe you’ve already found the solution but in case someone needs it, yours this.pessoasCursor.valueChanges(); is returning a Observable, it is necessary to register via subscribe to access their values, then:

this.pessoaService.getValues().subscribe(value => this.pessoa = value);

And in the HTML input switch to [(ngModel)]="pessoa.nome" and remove the formControlName="nome" for he is to reactive forms

stressing that today its getValues is not filtering by Id but searching for all people ordered by name, see:

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

Browser other questions tagged

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