1

I am quite new to Angular, Firestore and Firebase.

I have a component that fetches all my hero documents. I managed to fetch all heroes and list their names in a list. I am now trying to get the hero.id so that I can pass that id to my routing component and display a detail view for that hero. Though I can not manage to get the hero.id. How do you get the document id?

I tried to simply do: hero.id but it does not seem to work???

heroes.component.ts:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

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

  heroes: Observable<any[]>;

  constructor(db: AngularFirestore){
    this.recipes = db.collection('heroes').valueChanges();
  }

  ngOnInit() {
  }
}

heroes.component.html

<ul>
  <li class="text" *ngFor="let hero of heroes | async">
    <a routerLink="/hero/{{hero.id}}">{{hero.name}} -> id: {{hero.id}}</a>
  </li>
</ul>

Any help is much appreciated! Thanks! :)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
iSebbeYT
  • 1,441
  • 2
  • 18
  • 29
  • Presumably you read some document to learn about `valueChanges()`. The very same document would explain `snapshotChanges()`, with the explicit note that "This metadata provides you the underyling DocumentReference **and document id**. I wonder how you could have missed that. See https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md. –  Apr 28 '18 at 17:26

2 Answers2

4

ID is in record's metadata. Metadata can be received with snapshotChanges() (you use valueChanges()).

this.recipes = db.collection('heroes').snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data();
    const id = a.payload.doc.id;
    return { id, ...data };
  });
});

Now your observable broadcasts objects also with id property and you can use async pipe as you use now.

Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
0

just to know, can be like

getHeroes = async () => {
        try {
            const heroes= [];

            var ret = await db.collection('heroes').get();

            ret.docs.map((e) => {
                heroes.push({id: e.id, ...e.data()});
            });

            console.log(heroes);

        } catch (e) {
            console.log(e);
        }
}
Kevyn M
  • 11
  • 1