Let’s say we have a collection in our Firebase Database called survey and we want to perform the CRUD operations to manipulate this collection.

But, before we go there, first let’s look at the type of data the collection holds.
export interface ISurvey {
id?: string;
name: string;
desc: string;
isConfigured: boolean;
passScore: number;
}
Above is the survey interface in Angular which we are going to use as the type or document of surveys for our collection.
Create
saveSurvey(survey: ISurvey) {
return this.firestore.collection(COLLECTION_SURVEY).add(survey);
}
We are adding a new survey to the collection.
Read
getSurveys() {
return this.firestore.collection(COLLECTION_SURVEY).snapshotChanges();
}
Get the documents in the collection. The function actually returns an Observable, so to get the actual payload we need to subscribe to the function and parse the data to the needed type, see below.
surveys: ISurvey[];
getSurveys().subscribe(
(data) => {
this.surveys = data.map((e) => {
const s: ISurvey = e.payload.doc.data() as ISurvey;
s.id = e.payload.doc.id;
return s;
});
this.loading = false;
this._cd.markForCheck();
},
(error) => {
this.errorText = error;
this.loading = false;
this._cd.markForCheck();
}
);
Update
updateSurvey(survey: ISurvey) {
const id = survey.id;
delete survey.id;
return this.firestore.doc(`${COLLECTION_SURVEY}/` + id).update(survey);
}
Delete
deleteSurvey(surveyId) {
return this.firestore.doc(`${COLLECTION_SURVEY}/` + surveyId).delete();
}
All the above functions except getSurveys returns a promise, so you would use then() and catch() blocks to process the response. For example, say after deleting a survey we need to refresh the data. The we can do this on the then() block of the promise returned by the deleteSurvey method, see below for sample code.
this.deleteSurvey(survey.id)
.then(() => {
this.loading = false;
this.getSurveys();
})
.catch((error) => {
this.loading = false;
this.errorText = error;
}
);
Versions
- @angular/cli@~12.2.6
- @angular/fire@^7.1.1
**Soon I will share the complete code on Github.