I have an application running on angular 8 and firebase version 7.4.0 and now we are upgrading to angular 16 and firebase v10.
In the services we have used doc.snapshotChanges() to return an observable in the calling function and subscribe to it in the calling function and listen for changes and update the data.
home.component.ts:
import { Component, OnInit } from '@angular/core';
import { IssueManagementService } from "../services/issue-management.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
issues: any;
data: any;
constructor(private issueService: IssueManagementService) {}
async ngOnInit() {
this.data = await this.issueService.getAllDocuments();
this.data.subscribe(docs => {
this.issues = docs.map((doc: Object, index) => {
return {
...doc,
serial: index + 1,
id: doc['id']
}
})
// prints this line if any changes occur
console.log("Any changes in issues reflected here: ", this.issues);
})
}
}
issue-management.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class IssueManagementService {
private IssueCollection = "issues";
constructor(private db: AngularFirestore) { }
async getAllDocuments(param?) {
const snapshot = this.db.collection(this.IssueCollection, (ref) => {
let query: firebase.firestore.Query = ref;
if (typeof param !== 'undefined') {
query = query.where(param['key'], "==", param['value']);
}
query = query.orderBy("dateModified", "desc");
return query;
})
// return the observable to listen to changes
return snapshot.snapshotChanges().pipe(
map(snapshots => {
return snapshots.map((s: Object) => {
return {
...s['payload'].doc.data(),
id: s['payload'].doc.id
}
})
})
)
}
}
Now currently there is the compat version available from
import { AngularFirestore } from '@angular/fire/compat/firestore';
This let’s me keep the code as as without any changes. But I want to find the newer modular version as mentioned on the firebase website.
I found the onSnapshot method but it returns an unsubscribe object on which I cannot do .subscribe() and listen for value changes
I found a similar question here.
I tried implementing and converting the onsnapshot to observable, but that did not work either.
Any help is appreciated. I have been stuck on this problem for 3 days!