繁体   English   中英

RxJS 发出的值没有通过.pipe(...)

[英]Values emitted by RxJS Subject not going through .pipe(...)

在下面的代码中,我尝试构建一个 RxJS pipe 并使用pipe处理主题发出的值。 代码有效,但结果与我预期的不同。

const rxjs = require("rxjs");
var subject = new rxjs.Subject();

subject
.pipe(rxjs.tap(console.log('tap')))
.subscribe(console.log);

function sendRequest(requestID, cb) {
  var delay = Math.floor(Math.random() * (6 - 3 + 1)) + 5;
  var request = {
    hostname: "httpbin.org",
    headers: { "request-id": requestID },
    path: "/delay/." + delay,
  };
  require("http")
    .get(request, (res) => {
      var body = "";
      res.on("data", function (chunk) { body += chunk; });
      res.on("end", function () { cb(res, body); });
    })
    .end();
}

concurrentRequests(5);
function concurrentRequests(limit) {
  for (var i = 0; i < limit; i++) {
    sendRequest(i, function (res, body) {
      var reqID = JSON.parse(body).headers["Request-Id"];
      subject.next("Concurrent Response #" + reqID + " returned a " + res.statusCode);
    });
  }
}

我的目的是构建一个 pipe 来使用来自 RxJS 库的Subject处理每个发出的值,当我运行上面的代码时,我希望得到这个 output:

tap
Concurrent Response #1 returned a 200
tap
Concurrent Response #0 returned a 200
tap
Concurrent Response #2 returned a 200
tap
Concurrent Response #3 returned a 200
tap
Concurrent Response #4 returned a 200

但是 output 是:

tap
Concurrent Response #1 returned a 200
Concurrent Response #0 returned a 200
Concurrent Response #2 returned a 200
Concurrent Response #3 returned a 200
Concurrent Response #4 returned a 200

为什么发出的值没有通过 pipe?

subject.pipe(rxjs.tap(console.log('tap')))

您提供了一个值而不是回调:

subject.pipe(rxjs.tap(() => console.log('tap')))

您执行了console.log('tab')并将undefined的值传递给rxjs.tap ,而实际上您想添加一个观察者

暂无
暂无

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

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