在我的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
})
如何解决此问题?
答案 0 :(得分:2)
而不是:
resolve(this.acc.getCurrentAcceleration(this.onSuccess,this.onError));
执行:
this.acc.getCurrentAcceleration(resolve, reject);
您不需要this.onSuccess
。
答案 1 :(得分:0)
试试这样:
getAcceleration(): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.acc.getCurrentAcceleration()
.success(data => {
resolve(<any>data);
})
.error(() => {
reject('Failed to load profile');
});
})
}