-2

In my angularJS 4 app, I'm using a cordova accelerometer plugin called device motion for something. The api has a function call getAcceleration(successCallback,errorCallback). So i created a service that looks like this

 @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';
  }
}

In my component, I do this to try to get the return value from onSuccess callback function, however the response is undefined

 this.accelerationService.getAcceleration().then((res) =>{
              console.log(res); // res is undefined
          })

How can I resolve this issue?

jackjoesmith
  • 951
  • 4
  • 20
  • 33

2 Answers2

2

Instead of:

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

Do:

this.acc.getCurrentAcceleration(resolve, reject);

You don't need this.onSuccess.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

Try like this :

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