Property 'onSnapshot' does not exist on type 'AngularFirestoreCollection<unknown>'

限于喜欢 提交于 2020-07-22 08:49:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!