2017-10-19 9 views
-2

私のangularJS 4アプリでは、何かのためにデバイスモーションと呼ばれるコードホイール加速度計プラグインを使用しています。 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 
      }) 

どのようにすることができていますこの問題を解決しますか?

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

getCurrentAccelerationの戻り値ではなく、結果を使用して約束を解決する必要があります。 –

+0

これはobservalbesを使用して解決する必要があります – Nickolaus

+0

@Nickolausありがとうございます。私はobservablesをさらに見ていきます – joejoeso

答えて

2

の代わりに::

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

の操作を行います。

this.acc.getCurrentAcceleration(resolve, reject); 

あなたはthis.onSuccessを必要としない

+0

約束とコールバックはとても紛らわしいものです。助けてくれてありがとう – joejoeso

0

は次のように試してみてください。

関連する問題