im trying to implement a old cordova plugin who hasnt any native wrapper in ionic, i can load the plugin and console.log the data but i can't get the data to push it into an a global array, i get the error "accelerometerData is not defined" , this is the function im using to watch the plugin values:
// 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()....
}
if i try to console.log this.accelerometerData or try to access in any other functions the variable is null or undefined...
thanks in advance.
I found myself a solution wrapping the cordova callback into a promise, then use a interval to watch the data per x ms, finally define a timeout to clear the interval
// 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();