问题
I am trying to detach listener from cloud Firebase, but I still get this error.
Property 'onSnapshot' does not exist on type 'AngularFirestoreCollection'
Do you know, what sould I import? I directly copy this code from Firebase documentation.
let unsub = this.firestore.collection('cities').onSnapshot(() => {
});
// Stop listening for changes
unsub();
This is my constructor and import:
import { AngularFirestore } from "@angular/fire/firestore";
constructor(public firestore: AngularFirestore) {}
Thanks for your advices!
回答1:
AngularFirestore
is a class in the library angularfire
, according to the source code https://github.com/angular/angularfire/blob/master/src/firestore/firestore.ts#L106, the class AngularFirestore
does not contain any method called onSnapshot()
.
https://firebase.google.com/docs/firestore/query-data/listen
db.collection("cities").doc("SF")
.onSnapshot(function(doc) {
console.log("Current data: ", doc.data());
});
In this case db
is equal to firebase.firestore();
https://firebase.google.com/docs/firestore/quickstart
If you want to use AngularFire then you can use snpashotChanges()
:
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
来源:https://stackoverflow.com/questions/59358077/property-onsnapshot-does-not-exist-on-type-angularfirestorecollectionunknown