Angular + Firebase + Firestore: CRUD Operations
Angular + Firebase + Firestore: CRUD Operations
Firebase is a versatile cloud solution that supports a multitude of features, including a cloud-hosted, NoSQL database called Firestore. Integrating Firestore with Angular applications is straightforward using the AngularFire library.
In this guide, we'll create a simple CRUD (Create, Read, Update, Delete) application using Angular, Firestore, and AngularFire.
1. Set Up:
Install AngularFire & Firebase:
ng add @angular/fire
This command will prompt you for Firebase configuration settings. You can find these settings in your Firebase Console, under "Project Settings > General > Your apps > Firebase SDK snippet > Config."
2. CRUD Operations:
Create:
To add data to Firestore:
import { AngularFirestore } from '@angular/fire/firestore';
constructor(private db: AngularFirestore) {}
addData() {
this.db.collection('items').add({
name: 'NewItem',
description: 'This is a new item.'
});
}
Read:
To fetch all documents from a collection:
items: Observable<any[]>;
constructor(private db: AngularFirestore) {
this.items = db.collection('items').valueChanges();
}
In your template:
<ul>
<li *ngFor="let item of items | async">
{{ item.name }} - {{ item.description }}
</li>
</ul>
To fetch a specific document:
item: Observable<any>;
constructor(private db: AngularFirestore) {
const docRef = db.doc('items/itemId'); // replace 'itemId' with your specific document ID
this.item = docRef.valueChanges();
}
Update:
To update a specific document:
updateData() {
const docRef = this.db.doc('items/itemId'); // replace 'itemId' with your specific document ID
docRef.update({
description: 'Updated description.'
});
}
Delete:
To delete a specific document:
deleteData() {
const docRef = this.db.doc('items/itemId'); // replace 'itemId' with your specific document ID
docRef.delete();
}
3. Security:
Always set up Firestore security rules to prevent unauthorized access. This is crucial for production applications.
Example of a simple security rule that allows only authenticated users to perform CRUD operations:
service cloud.firestore {
match /databases/{database}/documents {
match /items/{itemId} {
allow read, write: if request.auth.uid != null;
}
}
}
Conclusion:
This guide gives a quick overview of integrating Firestore with Angular using AngularFire for CRUD operations. Always remember to implement authentication and set appropriate Firestore security rules before deploying applications to production.