问题描述
我是 RxJs 的新手,我有一个用于地理编码的 API,它提供了如下功能:
I am a newbie to RxJs and I have an API that I am using for geocoding that provides a function like the following:
simpleGeocode(options)
* where options = { address: {addr: ... }, success: Function, failure: Function}. The success function returns the geocoded LatLon object.
我在带有 NGRX 效果的 Angular 应用程序中使用它,所以我希望将它作为 Observable 使用,以便我可以使用标准效果设置,例如:
I am using this in Angular app with NGRX Effects and so I would like it to have it as an Observable so I can use the standard Effect setup like:
@Effect()
public calculateLocation: Observable<void> = this.actions
.ofType(actions.CALCULATE_LOCATION)
.switchMap((action) => {
let location = action.payload;
let options = {
address: location.address
};
// ...
this.geocodeService.simpleGeocode(options)
.map(latLon => new actions.CalculateLocationSuccessAction(latLon);
.catch(error => new actions.CalculateLocationFailureAction(error);
},
但我完全不知道如何包装该库调用以使其成为 Observable.我从 http 阅读了一些关于 bindCallback() 的信息://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindCallback 但我并不完全理解.我确实理解它需要一个回调方法作为函数的最后一个参数,所以它看起来不适合我的情况,因为成功和失败函数都作为对象的一部分传递到函数中.
But I am totally clueless as to how I would wrap that library call to make it into an Observable. I have read some information about bindCallback() from http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindCallback but I don't fully understand it. I did understand it requires a callback method to be the last parameter of the function so it doesn't look like it would work for my situation since both the success and failure functions are passed into the function as part of an object.
我如何从这个 API 方法中创建一个 Observable,将成功回调映射到 Observable 的下一个回调,并将失败映射到 Observable 的错误?
How would I make an Observable out of this API method that would map the success callback to the Observable's next and the failure to Observable's error?
推荐答案
你可以使用 Observable.create 来包装一个带有回调接口的外部库.
You can use Observable.create to wrap an external library with callback interface.
这样的事情应该可以工作:
Something like that should work:
Observable.create(observer => {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
observer.next(results);
observer.complete();
}
else {
observer.error(status);
}
});
});
这篇关于将 API 函数包装在 RxJs Observable 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!