为什么this.health在这种情况下不起作用



我正在创建一个使用healthkit的应用程序。当我运行应用程序时,我收到一个错误,说TypeError: Cannot read property 'health' of null。我试着做navigator.health,但得到的错误是健康状况在navigator上不存在。我认为这是一个需要解决的相当简单的问题,在这种情况下,我如何正确地调用health?

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);
})
}
}

编辑,链接到教程,为了简洁起见,我指的是this.health.query({。当我不包括代码的那一部分时,我不会得到这个错误。


edit2:已解决,只需使用箭头函数或新变量保留其值。

如果您正在使用Ionic的V3安装以下插件

$ ionic cordova plugin add cordova-plugin-health
$ npm install --save @ionic-native/health@4

在组件import { Health } from '@ionic-native/health';

最新更新