如何 return 从 cordova 插件 angular/ionic 回调数据

How to return callback data from cordova plugin angular/ionic

我正在尝试实现一个旧的 cordova 插件,它在 ionic 中没有任何本机包装器,我可以加载插件和 console.log 数据,但我无法获取数据以将其推送到全局数组中,我得到错误“accelerometerData is not defined”,这是我用来观察插件值的函数:

// plugin cordova-plugin-device-motion-fast

declare var navigator: any;
accelerometerData: any[]; //<--- global variable

startAccelerometer(){
    var options = { frequency: 75 };  // Update every x seconds
    var watchID = navigator.accelerometer.watchAcceleration(
      function accelerometerSuccess(acceleration){
          let data = {
            x: 0,
            y: 0,
            z: 0,
            roll: 0,
            pitch: 0,
            yaw: 0,
            timestamp: 0
          }
          data.x = acceleration.x;
          data.y = acceleration.y;
          data.z = acceleration.z;
          data.roll = acceleration.roll;
          data.pitch = acceleration.pitch;
          data.yaw = acceleration.yaw;
          data.timestamp = acceleration.timestamp;
          console.log(data) //<--- i see the data here
          this.accelerometerData.push(data); // <--- null || undefined || error isn't defined
          
        },
      function accelerometerError(error){
           console.log(error)
      }, options);
  }
  
  saveTheData(){ <--- save the data to api
   const data = {
   Accelerometer:  this.accelerometerData // <--- null || undefined || error isn't defined
   }
   this.saveToApi(data).subscribe()....
  }

如果我尝试 console.log this.accelerometerData 或尝试在任何其他函数中访问该变量为 null 或未定义...

提前致谢。

我自己找到了一个解决方案,将 cordova 回调包装成一个承诺,然后使用一个间隔来观察每 x 毫秒的数据,最后定义一个超时来清除间隔

// wrap the plugin
startAccelerometer(){
    return new Promise((resolveCallback, rejectCallback) =>{
     new Promise((resolve, reject) =>{
      navigator.accelerometer.watchAcceleration(resolve,reject);
     }).then((acceleration) => {
        resolveCallback(acceleration);
     }).catch((error) =>{
       rejectCallback(error);
     });
    });
  }
  
 // usage
getData(){
  const frequency =  75;
  const duration = 30000;
  var watchID = setInterval(() => this.getData(),frequency);
  this.startAccelerometer().then((accelerometer) =>{
    console.log(accelerometer);
  });
  setTimeout(() => clearInterval(watchID),duration);
}
   
   //call the getData()
   this.getData();