angular - 检测客户端代码中 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
应用程序一起使用。
解决方案
部分解决方案
以下代码将允许您收听单个集合。目前没有办法跨多个项目文档收听子集合。最好的解决方案是对您的数据模型进行反规范化,以便您拥有一个名为的集合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.
// ...
}
});
推荐阅读
- dialogflow-es - Google Actions:调用名称重复
- vb.net - datagridview 2表错误输出
- delphi - 有没有一种有效的方法可以在运行时将 png-Images 加载到 FMX 中的 TImage 对象中?
- sql - 是否有用于 SQL 的查找和替换功能
- azure - Azure 手臂模板验证
- javascript - 画布地图坐标
- spring - Spring Security does not intercept requests
- android - 获取正确的联系人计数,但在 Ionic 4 中获取联系人的空值
- actions-on-google - The command STOP doesn't close the action during mediaobject playback
- excel - C#如何在Excel VSTO AddIn中关闭excel应用程序