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

Why does this.health not work in this instance?

我正在创建一个使用 healthkit 的应用程序。当我 运行 应用程序时,我收到一条错误消息 TypeError: Cannot read property 'health' of null。我尝试执行 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);

    })
  }
}

编辑,link 教程,为了简洁起见,我指的是 this.health.query({。当我不包括该部分代码时,我不会收到此错误。


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

如果您使用的是 Ionic V3,请安装以下插件

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

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