在我的angularJS 4应用程序中,我使用了称为设备运动的cordova加速度计插件。 api有一个函数调用getAcceleration(successCallback,errorCallback)。所以我创建看起来像这样如何在此承诺中返回回调中的值?
@Injectable()
export class AccelerometerService {
private acc : any;
constructor(private winRef:WindowRef) {
this.acc = this.winRef.nativeWindow.plugins.navigator.accelerometer;
this.onSuccess = this.onSuccess.bind(this);
this.onError = this.onError.bind(this);
}
getAcceleration(){
return new Promise ((resolve, reject) =>{
resolve(this.acc.getCurrentAcceleration(this.onSuccess,this.onError));
});
}
onSuccess(acceleration){
return acceleration; // value that I want returned to my component
}
onError(){
return 'error';
}
}
在我的组件服务,我这样做是为了尽量摆脱的onSuccess回调函数的返回值,但此时反应是不确定的
this.accelerationService.getAcceleration().then((res) =>{
console.log(res); // res is undefined
})
我怎样才能解决这个问题?
您需要解决承诺与结果,而不是返回getCurrentAcceleration。 –
这应该使用observalbes解决 – Nickolaus
@Nickolaus谢谢。我会更注意观察 – joejoeso