将API函数包装在RxJs Observable中 [英] Wrap an API function in an RxJs Observable

查看:85
本文介绍了将API函数包装在RxJs Observable中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是RxJ的新手,我有一个用于地理编码的API,该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.

我正在Angular应用中使用NGRX特效,因此我希望它具有可观察性,因此我可以使用标准的特效设置,例如:

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 ://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方法制作可观察对象,该方法将成功回调映射到可观察对象的下一个对象,将失败回调映射到可观察对象的错误?

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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆