Display in ngModel return from FireStore

0

How to display the data returned from the FireStore in an Angular ngModel directive?

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

person.model.ts:

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

person.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();
  }

person-view.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">
    
asked by anonymous 31.01.2018 / 00:16

1 answer

0

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

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

And in HTML input change to [(ngModel)]="pessoa.nome" and remove formControlName="nome" because it is reactive forms

Noting that today your getValues is not filtering by Id and looking for all people by name, see:

this.afs.collection('pessoas', ref => ref.orderBy('nome', 'asc'));
    
15.10.2018 / 05:24