在我的 Angular6 项目中,我有一个“协作者”页面。显示协作者很容易,但现在我需要确定用户何时不在页面上(或跳出),以便我可以删除图标。
I do not want to debug the code Im hoping i can find better logic. The code is less important at this point
我的尝试
当任何用户更新页面上的
数据
时,都会更新修改
时间戳。update_data() { db.object('dataRef').update({modified: Date.now()}) }
由于所有用户都订阅了
data
observable;在数据
更改时,我使用相同的标记更新所有用户对象(现在我知道谁获得了最后的更新)// on data updated this.data.subscribe( res => { this.user.update({modified: Date.now()}) });
现在我知道谁获得了数据更新;在 html 中,我将用户时间戳与“上次修改的数据”时间戳进行比较。如果时间戳不匹配,那么我就知道用户离开了页面。
<div *ngIf="user.modified===data.modified"> <!-- show this user icon because they recieved the last update --> </div>
这可行,但似乎很复杂,并且数据更新和用户获得更新之间存在延迟 - 导致前端挑战
这对我有用
基于Mium的回答
组件
document.addEventListener("visibilitychange", function() {
let visible = document.visibilityState==='visible';
self.configsService.update_collab_visible(visible); // <= updates the db with true or false
});
html
<div *ngIf="user.visible">
{{user.initial}}
</div>
最佳答案
检测用户是否在您的选项卡上处于事件状态的更好方法是检测可见性状态。
VisibilityChange API:
The Document.visibilityState read-only property returns the visibility of the document, that is in which context this element is now visible. It is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering. more : https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
因此,首先,对于每个用户,您可以更有效地检测其存在:
document.addEventListener("visibilitychange", function() {
console.log( document.visibilityState );
// send notification to firebase
});
从这一步开始,您可能遇到的唯一延迟将与 firebase 密切相关。因此,您需要配置同步频率,或者如果您确实想要更快,请使用 WebSocket 连接。
关于javascript - 显示活跃用户图标 - 如何确定谁不再在线(寻找 NG 或 JS 解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317244/