2017-10-19 101 views
-2

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

您需要解决承诺与结果,而不是返回getCurrentAcceleration。 –

+0

这应该使用observalbes解决 – Nickolaus

+0

@Nickolaus谢谢。我会更注意观察 – joejoeso

回答

2

相反的:

resolve(this.acc.getCurrentAcceleration(this.onSuccess,this.onError)); 

务必:

this.acc.getCurrentAcceleration(resolve, reject); 

你不需要this.onSuccess

+0

承诺和回调对我来说是如此令人困惑。谢谢您的帮助 – joejoeso

0

尝试这样的:

getAcceleration(): Promise<any> { 
    return new Promise<any>((resolve, reject) => { 
     this.acc.getCurrentAcceleration() 
      .success(data => { 
       resolve(<any>data); 
      }) 
      .error(() => { 
       reject('Failed to load profile'); 
      }); 
    }) 
}