【问题标题】:Angularfire snapshotChanges() vs Firestore javscript library onSnapshot()Angularfire snapshotChanges() vs Firestore javscript 库 onSnapshot()
【发布时间】:2020-04-06 06:52:58
【问题描述】:

我发现 firestore 有两个实时监听器。

  • Angularfire:snapshotChanges()
  • Firestore Javascript 库:onSnapshot()

这是我的问题

  1. 我可以知道有什么区别吗?我应该如何正确使用它们(我正在使用 Ionic + Cordova + Angular 框架进行开发)?
  2. 如何分离 snapshotChanges()?请参阅 Firestore 文档,我可以按照以下方式分离 onSnapshot()。
    var unsubscribe = db.collection("cities")
        .onSnapshot(function (){
          // Respond to data
          // ...
        });

    // Later ...

    // Stop listening to changes
    unsubscribe();

感谢您的友好分享。

【问题讨论】:

  • 你在哪里看到 angularfire 中的 onsnasphot?
  • 感谢您的指出。我已经更新了我的帖子,其中 onsnapshot() 来自 JS Web 库,而 snapshotChanges() 来自 angularfirestore。似乎我也可以在 angularfirestore 下使用 onsnapshot ,两者都工作得很好,所以我想知道它们之间有什么区别,使用它们的最佳情况是什么。 listener = this.afs.doc(test/${id}/).ref.onSnapshot() listener = this.afs.doc(test/${id}/).snapshotChanges().subscribe()
  • 如果你使用 angularfire,那么只需使用snapshotChanges(),如果你使用 js web 库,那么使用onSnapshot(),两者都会实时检索数据。但是snapshotChanges() 是 angularfire 库中的一种方法,您在 Angular 项目中工作时会使用它

标签: firebase google-cloud-firestore angularfire2


【解决方案1】:

AngularFire 库不包含名为 onSnapshot() 的方法。 onSnapshot() 方法用于 javascript cloud firestore 库中,用于监听实时更新。

虽然 snapshotChanges() 专门用于 angularfire,但它会返回 Observable,因此它将继续侦听数据库中的任何更改并检索数据。

unsubscribe,只需要调用方法unsubscribe()

//Subscribe
subscription = this.itemRef.snapshotChanges().subscribe();

//Unsubscribe
subscription.unsubscribe()

【讨论】:

  • snapshotChanges() 返回的 Observable 持有什么?
  • Observable 将观察来自参考位置的数据流,然后当您调用subscribe() 时,您可以访问数据。 @arcrub
猜你喜欢
  • 2021-11-09
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2018-03-25
  • 2018-10-02
相关资源
最近更新 更多