Firebase如何知道特定客户端处于离线状态? [英] Firebase how to know specific client is offline?

查看:106
本文介绍了Firebase如何知道特定客户端处于离线状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用树莓派和Firebase开发设备/产品...

I am developing a device/product using raspberry pi and Firebase...

系统流程如下:用户在我的网站上购买设备,并且她可以使用相同的凭据登录移动应用.

System flows like this: user buys device on my website and she can use same credentials to login mobile app.

当前,我依赖于我如何将生成的uniuqe id放到设备中,以便从设备和设备到Firebase Realtime Database与db进行交互...

Currently, I am relying on an some how generated uniuqe id put by me in to device to interact to db from device and device to Firebase Realtime Database...

现在,我需要知道设备是在线还是离线.答案应该是可能的两种解决方案.因为我想通知用户:您的设备已离线" ...

Now I need to know if device is online or offline. Answers should be on possibble two solutions. Because I want to notify user: "Your device is offline"...

1-当前代码(取决于唯一ID):如果可能,我该如何实现.

1- on current code(relying on unique id): if it's possible, how can I achive this.

2-将系统更改为基于用户的:如果我执行此操作,必须如何思考系统.设备将没有显示输入,也没有键盘.例如,当用户更改密码时会发生什么?

2- changing system in to user based: if I implement this how I must think system. Device will have no display input nor keyboard. For example what happens when user changed her password?

谢谢..

推荐答案

您想要的是 onDisconnect

What you want is onDisconnect

设备启动时,您可以设置onDisconnect来更改其状态,甚至触发时间:

When your device starts you setup an onDisconnect to change its status or even fire a time:

var lastOnlineRef = firebase.database().ref("devices/1234/lastOnline");
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);

var isOnlineRef = firebase.database().ref("devices/1234/isOnline");
isOnlineRef.onDisconnect().set(false);

对于用户而言,我不确定自己是否理解.如果您使用UID在以下路径中隔离设备:/devices/UID,它们独立于用户而存在.

As to the user thing I'm not totally sure I understand. If you isolate your devices with your UID in a path like: /devices/UID they exist independently of the users.

对于您的用户,您只需创建所有设备的列表即可:/users/UID/devices

For your users you would simply create a list of all of their devices: /users/UID/devices

{
    1234: 1234,
    5678: 5678
}

然后在您的应用中,您首先要获取其设备列表,然后创建对它们的引用.

Then in your app you just first get their list of devices, then create references to them.

在Angular中,外观如下:

In Angular that would look like:

// in the ts
public userDevices = this.db.list('/users/UID/devices').valueChanges();

public getDeviceObservable(deviceId: string) {
    return this.db.object('/devices/' + deviceId).valueChanges();
}

//in the template
<div *ngFor="let deviceId of userDevices | async">
    <ng-container *ngIf="getDeviceObservable(deviceId) | async as device">
    {{ device | json }}
    </ng-container>
</div>

将getObservable放在模板中并不是完全最佳的做法,您也可以在组件中进行操作,但这与switchMap等有关.

It's not totally best practice to put a getObservable in the template, you could do it in the component too but thats a whole other talk with switchMap etc.

这篇关于Firebase如何知道特定客户端处于离线状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆