Reputation: 195
Ive been trying to get my head around v7 without too many docs available. Ive come up with code to (well trying too) query a collection and display in Angular (see below):
async getAppointments() {
const userId = await this.auth.currentUser?.uid;
console.log('Get Appointments: ' + userId);
const appRef = collection(this.afs, 'appointments')
const appQuery = query(appRef, where('uid', '==', userId));
const querySnapshot = getDocs(appQuery);
this.appt = (await querySnapshot).forEach((d) => {
const id = d.id;
const data = d.data as Appointment;
console.log(id, "=>", data);
return {id, ...data};
})
}
in the HTML *ngFor="let a of appt | async"
Firestore Timestamp: {{ a.start }}
Bt nothing shows. Im getting the document ID in the console log . Any ideas will be very helpful.
Thanks
Upvotes: 0
Views: 1770
Reputation: 195
After a bit of digging I finally cracked it....
async getAppointments() {
// This retrieves the chosen collection
const appointmentCollection = collection(this.afs, 'appointments').withConverter<Appointment>({
fromFirestore: snapshot => {
const { start, finish, comments } = snapshot.data();
const { id } = snapshot;
const { hasPendingWrites } = snapshot.metadata;
return { id, start, finish, comments};
},
toFirestore: (it: any) => it,
});
const uid = await this.auth.currentUser?.uid
const appQuery = query(appointmentCollection, where('uid', '==', uid));
this.appointments = collectionData(appQuery).pipe(
traceUntilFirst('appointments')
)
}
Appointment is from export type Appointment = {...} appointments is an Observable<Appointment[]>
Used *ngFor in html to display the data.
Getting a single document was even easier...
userDoc: DocumentReference;
snapped$: any;
async getUserDoc() {
const userId = await this.auth.currentUser?.uid;
this.userDoc = doc(this.afs, 'users/' + userId);
this.snapped$ = (await getDoc(this.userDoc)).data();
}
First checking I have the logged in userID.
Then *ngIf="snapped$"
in html
hope this helps anyone else...😎
Upvotes: 3