在我的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