首页 > 解决方案 > 检测客户端代码中 Firestore db 节点的更改

问题描述

你能告诉我如何在客户端代码(.ts文件)中检测 Firestore db 节点的变化吗?我知道如何使用云功能做到这一点。但是我怎样才能在客户端代码中做到这一点?

Firestore 节点: projects/{id}/transactions/

我的要求是:如果上述节点有任何变化,我需要升级提供者的(即projectProvider)共享属性值。我怎样才能做到这一点?

举个例子:

onWrite事件非常适合我的用例。但是我怎样才能在客户端.ts文件中实现它呢?

这是node.js云功能的实现。我怎样才能在客户端.ts文件上做这样的实现?

// Listen for any change on document `marie` in collection `users`
exports.myFunctionName = functions.firestore
    .document('users/marie').onWrite((change, context) => {
      // ... Your code here
    });

注意:angularfire2与我的ionic 3应用程序一起使用。

标签: angulartypescriptfirebaseionic3google-cloud-firestore

解决方案


部分解决方案

以下代码将允许您收听单个集合。目前没有办法跨多个项目文档收听子集合。最好的解决方案是对您的数据模型进行反规范化,以便您拥有一个名为的集合projectTransactions,并使用字段过滤客户端查询,projectId并使用安全规则强制访问。

该代码使用该docChanges方法,它允许您仅查看对集合所做的更改,而无需遍历每个文档。这种方法在文档的“查看快照之间的更改”部分中进行了讨论,当它说

在查询快照之间查看查询结果的实际变化通常很有用,而不是简单地使用整个查询快照。

const firebase = require('firebase');
require("firebase/firestore");

// Initialize Firebase
let config = {
  apiKey: "*** Your API key ***",
  authDomain: "*** Your Auth domain ***",
  databaseURL: "*** Your database URL ***",
  projectId: "*** Your project ID ***",
  messagingSenderId: "*** Your Messaging Sender ID ***"
};
firebase.initializeApp(config);

let email = 'my.name@example.com';
let password = 'myExamplePassword';

firebase.auth().signInWithEmailAndPassword(email, password)
  .catch(error => {
    console.log(error);
  });

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log('I am logged in');

    // Initialise Firestore
    const firestore = firebase.firestore();
    const settings = {timestampsInSnapshots: true};
    firestore.settings(settings);

    return firestore
    .collection('projectTransactions')
    .onSnapshot((querySnapshot) => {
      console.log('Listening to the projectTransactions collection');
      querySnapshot.docChanges().forEach((change) => {

        // A new transaction has been added
        if (change.type === 'added') {
          console.log(`A new transaction has been added with ID: ${change.doc.id}`);
        }

        // A transaction has been deleted
        if (change.type === 'removed') {
            console.log(`A transaction has been removed with ID: ${change.doc.id}`);
        }

      });
    });

  } else {
    // User is signed out.
    // ...
  }
});

推荐阅读