【发布时间】:2020-08-04 23:24:09
【问题描述】:
我正在创建一个使用 healthkit 的应用程序。当我运行应用程序时,我收到一条错误消息 TypeError: Cannot read property 'health' of null。我尝试做 navigator.health,但得到的错误是 navigator 上不存在健康。我认为这是一个相当容易解决的问题,在这种情况下如何正确调用健康?
import { Component } from '@angular/core';
import { Platform } from "@ionic/angular";
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { Health } from '@ionic-native/health/ngx';
declare var shake;
var min_speed = 0.2;
@Component({
selector: 'app-motion-analysis',
templateUrl: './motion-analysis.page.html',
styleUrls: ['./motion-analysis.page.scss'],
})
export class MotionAnalysisPage {
constructor(public platform: Platform, private health: Health){}
ionViewDidEnter() {
this.platform.ready().then(() => {
this.health.isAvailable()
.then((available:boolean) => {
console.log(available);
this.health.requestAuthorization([
{
read: ['steps'], //read only permission
}
])
.then(res => console.log(res))
.catch(e => console.log(e));
})
.catch(e => console.log(e));
function onShake() {
console.log("shake")
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 1000,
timeout: 10000,
enableHighAccuracy : true,
});
function onSuccess(position){
if(position.coords.speed > min_speed){
this.health.query({
startDate: new Date(new Date().getTime() - 10*1000 ), // ten sec ago
endDate: new Date(), // now
dataType: 'steps',
limit: 1000
}).then(data=>{
console.log(data);
}).catch(e => {
console.log("error "+ e);
})
}
}
};
function onError(err) {
console.log(err)
};
// Start watching for shake gestures and call "onShake"
shake.startWatch(onShake, 5, onError);
})
}
}
编辑,link 到教程,为了简洁起见,我指的是this.health.query({。当我不包含该部分代码时,我不会收到此错误。
edit2:已解决,只需使用箭头函数或新变量保留 this 的值。
【问题讨论】:
标签: javascript android angular cordova