简体   繁体   English

如何从节点请求创建RxJs Observable

[英]How to create an RxJs Observable from a node request

Currently can create an observable explicitly as follows: 目前可以明确地创建一个observable,如下所示:

const Rx = require("rxjs");
const request = require("request");

        return Rx.Observable.create(function (observer) {
            request(options, function (error, response, body) {
                if (error) {
                    observer.error(error);
                } else {
                    observer.next(response);
                    observer.complete();
                }
            });
        });

Is there a shorthand way to do this with the RxJs library (or another library)? 有没有一种简便的方法来使用RxJs库(或其他库)?

Here is my solution: 这是我的解决方案:

    return (options) => {
        const boundCallback = Rx.Observable.bindNodeCallback(request, toResponseOnly);
        return boundCallback(options);
    };

function toResponseOnly(response) {
    return response;
}

The second function is required to ensure only the response is passed on, otherwise the params to the callback are passed on as an array. 第二个函数需要确保仅传递响应,否则回调的参数将作为数组传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM