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

과 같은 서비스를 만들어,이 그러나 응답이

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

어떻게 내가 할 수있는 정의되지는 onSuccess 콜백 함수의 반환 값을 얻기 위해 시도 할 이 문제를 해결 하시겠습니까? 이 같은

+0

getCurrentAcceleration이 반환되지 않고 결과로 약속을 해결해야합니다. –

+0

이것은 observalbes를 사용하여 해결해야합니다. – Nickolaus

+0

@ Nikolaus 감사. 나는 관측 가능을 더 보게 될 것이다. – 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'); 
      }); 
    }) 
} 
관련 문제