【发布时间】:2024-05-20 18:30:02
【问题描述】:
在我的 angularJS 4 应用程序中,我使用了一个名为 device motion 的 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
})
我该如何解决这个问题?
【问题讨论】:
-
你需要用结果来解决promise,而不是getCurrentAcceleration的返回。
-
这应该使用 observalbes 解决
-
@Nickolaus 谢谢。我会更多地研究 observables
标签: javascript angular promise