Ich versuche, meine Dokumente mit der ID abzurufen, kann es aber nicht herausfinden.
Derzeit rufe ich meine Dokumente folgendermaßen ab:
const racesCollection: AngularFirestoreCollection<Races> = this.afs.collection('races');
return racesCollection.valueChanges();
Ich bekomme meine Dokumentenliste zwar einwandfrei, es gibt jedoch keine Dokument-ID.
Wie kann ich es für jedes Dokument abrufen?
Ich habe endlich die Lösung gefunden. Victor war nahe an den Doc-Daten.
const racesCollection: AngularFirestoreCollection<Race>;
return racesCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Race;
data.id = a.payload.doc.id;
return data;
});
});
ValueChanges () enthält keine Metadaten, daher müssen wir SnapshotChanges () verwenden, wenn wir die Dokument-ID benötigen, und sie dann wie hier angegeben richtig zuordnen https://github.com/angular/angularfire2/blob/master/docs/ firestore/collect.md
Um die ID der Dokumente in einer Sammlung zu erhalten, müssen Sie snapshotChanges()
verwenden.
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
Dokumentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example
Für winkel6 +
this.shirtCollection = afs.collection<Shirt>('shirts');
this.shirts = this.shirtCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
doc.id
Erhält die UID.
Kombinieren Sie mit dem Rest der Daten für ein Objekt wie folgt:
Object.assign({ uid: doc.id }, doc.data())
Für angular 8 und Firebase 6 können Sie das Options-ID-Feld verwenden
getAllDocs() {
const ref = this.db.collection('items');
return ref.valueChanges({idField: 'customIdName'});
}
dadurch wird die ID des Dokuments für das Objekt mit einem angegebenen Schlüssel (customIdName) hinzugefügt.
ID kann vor dem Hinzufügen von Dokumenten in der Datenbank abgerufen werden:
var idBefore = this.afs.createId();
console.log(idBefore);
Habe das probiert
colWithIds$<T>(ref: CollectionPredicate<T>, queryFn?): Observable<any[]> {
return this.col(ref, queryFn).snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
}));
}
aber ich stoße auf diesen fehler
[ts] Spread-Typen dürfen nur aus Objekttypen erstellt werden