javascript - 显示活跃用户图标 - 如何确定谁不再在线(寻找 NG 或 JS 解决方案)

标签 javascript angular rxjs

在我的 Angular6 项目中,我有一个“协作者”页面。显示协作者很容易,但现在我需要确定用户何时不在页面上(或跳出),以便我可以删除图标。

I do not want to debug the code Im hoping i can find better logic. The code is less important at this point

我的尝试

  1. 当任何用户更新页面上的数据时,都会更新修改时间戳。

    update_data() {
        db.object('dataRef').update({modified: Date.now()})
    }
    
  2. 由于所有用户都订阅了 data observable;在数据更改时,我使用相同的标记更新所有用户对象(现在我知道谁获得了最后的更新)

    // on data updated
    this.data.subscribe( res => {
        this.user.update({modified: Date.now()})
    });
    
  3. 现在我知道谁获得了数据更新;在 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/

相关文章:

javascript - jQuery - 调整图像大小以适应 div

javascript - 让 ng-repeat 在 AngularJS 的 $interpolate 服务中工作

javascript - 引用错误: variable is not defined after if statement

typescript - rxjs 管道和订阅(在主题上)在两个单独的步骤中没有按预期工作

asp.net - 如何在 ASP.NET GridView 中找到控件的客户端 ID?

angular - 以编程方式将投影内容传递给 child ? (否则将被渲染成 <ng-content> )

angular - 伪元素的样式 z-index

javascript - ngx-datatables 在排序时给出 "rxjs_1.fromEvent is not a function"错误

javascript - 如何在rxjs中检查Observable数组的长度

javascript - node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10) : 中出现错误