3
votes

I am trying to retrieve a single document from a firestore sub collection: database/users/uid/animal/docID

I am able to get the docID parsed from another component successfully but I am struggling with retrieving the information to display in html:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { AngularFireAuth} from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Router, ActivatedRoute } from '@angular/router';

interface Animal {
 name: string;
 age: number;
 sex: string;
 breed: string;
 colour: string;
 }

 interface animID extends Animal {
   id: string;
 }

  @Component({
  selector: 'app-detail-animal',
  templateUrl: './detail-animal.component.html',
  styleUrls: ['./detail-animal.component.css']
})
export class DetailAnimalComponent implements OnInit {

 curUser: any; // This used to maintain the logged in user. 
 animalDoc: AngularFirestoreDocument<Animal>;
 animalCol: AngularFirestoreCollection<Animal>;
 animalInfo: any;
 petID: Observable<Animal>;

 constructor(
  public auth: AuthService, 
  private afs: AngularFirestore, 
  private afAuth: AngularFireAuth, 
  private router: Router,
  public route: ActivatedRoute
  ) {
  const petID: string = route.snapshot.paramMap.get('id'); 
  console.log('AnimId from route: ', petID)
  const user: any = this.afAuth.authState
 }
 private curPetID: string = this.route.snapshot.paramMap.get('id');

 ngOnInit() {
  this.afAuth.auth.onAuthStateChanged((user) => {

  if (user) {
    // get the current user    
    this.curUser = user.uid;
    console.log('Animal ID:', this.curPetID )
    console.log('Current User: ', this.curUser);
    // Specify the Collection
    this.animalInfo = this.afs.collection(`users/${this.curUser}/animals/`, 
    ref => ref.where('id', "==", this.curPetID)
        .limit(1))
        .valueChanges()
        .flatMap(result => result)
        console.log('Got Docs:', this.animalInfo);
      }
    });
  }
}

Then in my HTML(only getting it display for now):

<strong>Name: {{ (animalInfo | async)?.name }}</strong>
<br>Breed: {{ (animalInfo | async)?.breed }}
<br>Animal System ID: {{ (animalInfo | async)?.id }}

When I run the code, in console.log('GotDocs: ', this.animalInfo) returns undefined.

Got Docs: 
 Observable {_isScalar: false, source: Observable, operator: MergeMapOperator}
 operator:MergeMapOperator {project: ƒ, resultSelector: undefined, concurrent: 
 Infinity}
 source:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar:false
__proto__:
Object

I am not sure if having the above code in ngOnInit() is the right way to go about this either.

Any help greatly appreciated.

Michael

3

3 Answers

5
votes

There is an easier approach for reading a single document. You already have the ID, so you can point to that specific document inside ngOnInit:

const docRef = this.afs.doc(`users/${this.curUser}/animals/${this.curPetID}`)
this.animalInfo = docRef.valueChanges()

Ideally, you unwrap this data in the HTML and set a template variable.

<div *ngIf="animalInfo | async as animal">

  Hello {{ animal.name }}

</div>

Or you can subscribe to it in the component TypeScript.

animalInfo.subscribe(console.log)
0
votes

animalInfo is observable type.

Angular2+ supports '| async' pipeline to show observable type directly. So, if you want to get real data value, you should use subscribe like this:

const collection$: Observable<Item> = collection.valueChanges()
collection$.subscribe(data => console.log(data) )

I hope this would be helpful :)

0
votes

Like @JeffD23 said:

you want to do the "(animalInfo | async) as animal" in an ngIf (recommended solution)

then you do not need the async pipe anymore in your html, do remember to use the new name in the brackets {{}}. if you forgot the names that you gave to your object just use the {{ animal | json }} this will show the Object as json text.

const ref = 'location in db';
const animalInfo$: Observable<Item>;
constructor(private service: Firestore) {
  this.animalInfo$ = this.service.doc(ref).valueChanges();
}

or you could do the async part in the constructor()/onInit() (backup solution)

const ref = 'location in db';
const animalInfo: Item;
constructor(private service: Firestore) {
  this.service.doc(ref).subscribe(item => {
    this.animalInfo = item;
    console.log(item);
  );
}

then you can do this again in your html {{ animalInfo | json }}