2017-10-19 106 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'); 
      }); 
    }) 
}