How to read, create/update and remove, listen on/off from the firebase database in Web(Angular)?
In the firebase database, sometimes we need to only read value. But for the admin panel, we need to read, write and delete values in the database
Let’s look at these operations
- read — When we need to show the data on the client-side or in the admin side.
Let’s create a firebase-db.service.ts file
import { Inject, Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';@Injectable()
export class FirebaseDbService {constructor(
private db: AngularFireDatabase
) { }getData(nodeKey: string) {
return return this.db.database.ref("our node key").once('value');
}}
In the componet.ts file. Firstly we provide the service in its module and then import that in the component and create an instance in the constructor
export class MyComponetn implements OnInit {constructor(
private firebaseDbService: FirebaseDbService
) { }ngOnInit(): void {
this.firebaseDbService.getData()
.then(snapshot => {
console.log(snapshot);
})
.catch(err => {
//handle error
})
}
In the above, it will fetch data only once from the firebase in the ‘our node’ key
2. update — We need to update the value in ‘our node’ key. We will create updateData function in the firebase database service
updateData(nodeKey: string) {
return this.db.database.ref(`our node`).update(data);
}
3. delete — When we need to delete the data or value from the node. Firstly we will create the deleteData function in the firebase database service.
deleteData(nodeKey: string) {
return this.db.database.ref(`our node`).remove();
}
Listen on/off in Firebase Database
Now we will add listener/subscription on/off
import { AngularFireDatabase } from '@angular/fire/database';
import { Component, OnInit, HostListener, NgZone } from '@angular/core';export class MatchPanelComponent implements OnInit {dbRef!: any;//declare variableconstructor(
private zone: NgZone,
private db: AngularFireDatabase
) {}databaseReference() {
this.dbRef= this.db.database.app.database().ref('/our node key/' + this.key);//Set Listener, whenever value changes in the our node key
this.dbRef.on('value', (data: any) => {
if (data.val()) {
this.zone.run(() => {
//set data inside ngZone
});
}
})
} ngOnDestroy() {
if (this.dbRef && this.dbRef.off)
this.dbRef.off(); // turn off to avoid memory leak and unnecessary listen on data which we don't want to receive
}
}
Reference for the firebase Javascript V8 Version https://firebase.google.com/docs/reference/js/v8
Thanks for reading.
Enjoy firebase with Angular and Javascript 😎