# 采样数据 Sample

了解如何操作样本数据 Sample 通过本节,您将学会

# 查询以及监听Sample

下面我们通过获取心率来阐述如何使用Sample的接口

# 查询当前的心率

假设现在我们要获取用户当前这个时刻的心率和步数数据,可以通过下面的代码实现

import health from '@service.health'
health.getRecentSamples({
    dataTypes: [health.DATA_TYPES.HEART_RATE,health.DATA_TYPES.STEP_COUNT],
    success: (res) => {
        console.log(`current heart rate(${res[0].dataType}) is`, res[0].data.value, 'bpm')
    }
})
1
2
3
4
5
6
7

# 监听心率的变化

假设现在我们要实时展示用户心率数据的变化,可以通过下面的代码实现

import health from '@service.health'
health.subscribeSample({
    dataType: health.DATA_TYPES.HEART_RATE,
    success: (res) => {
        console.log(`current heart rate(${res.value}) is`)
    }
})
1
2
3
4
5
6
7

# 取消监听心率的变化

取消用户心率监听的接口

import health from '@service.health'
health.unsubscribeSample({
    dataType: health.DATA_TYPES.HEART_RATE
})
1
2
3
4