简体   繁体   English

如何按顺序订阅并仅返回 RxJS 中最后一个 observable 的值?

[英]How do I subscribe in sequence and return only the value from the last observable in RxJS?

I'm in an Angular route resolver and want to return an observable.我在一个 Angular 路由解析器中,想要返回一个可观察的。

I need to subscribe to multiple async processes in order:我需要按顺序订阅多个异步进程:

A => B(a) => C(b) A => B(a) => C(b)

C depends on B and B depends on A. A must complete, then B, then C, but I only want the value from C to be used to cause the route to resolve. C 依赖于 B,B 依赖于 A。A 必须完成,然后 B,然后 C,但我只想使用 C 中的值来解决路由。

I've tried two different approaches:我尝试了两种不同的方法:

return A.pipe(
  concatMap(a => 
    B(a).pipe(
      concatMap(b => 
        C(b).pipe((c) => c); // also tried of(c)
      )
    )
  )
);

I've also tried我也试过

return A.pipe(
  concatMap(a => {
    return B(a).pipe(map(b => {a: a, b: b});
  ),
  concatMap({a, b} => {
    return C(b);
  )
);

How do I subscribe to A, then B, then C..., and then only get the value from the innermost observable?我如何订阅 A,然后是 B,然后是 C...,然后只从最里面的 observable 中获取值?

If I put a tap after my last concatMap I get my expected return value.如果我在最后一个 concatMap 之后点击,我会得到预期的返回值。 But my resolver never resolves?但是我的解析器永远不会解析? (or the wrong thing is getting emitted? I cannot really tell.) (或者发出了错误的东西?我真的不能说。)

If one of the observables in the chain never completes (like route params or query params), it'll halt the whole train.如果链中的一个 observables 永远不会完成(如路由参数或查询参数),它将停止整个火车。

switchMap should do: switchMap应该这样做:

A.pipe(
    switchMap(B), // which is more or less the same as `switchMap(a => B(a))`
    switchMap(C),
).subscribe(//...

Route resolvers need to complete before the Angular Router will continue.路由解析器需要在 Angular 路由器继续运行之前完成。 This is the same for route guards also.路线守卫也是如此。 Adding a operator that takes an emission, such as take(1), or first() and completes will solve the problem.添加一个接受发射的运算符,例如 take(1) 或 first() 并完成将解决问题。

return A.pipe(
  concatMap(a => {
    return B(a).pipe(map(b => {a: a, b: b});
  ),
  concatMap({a, b} => {
    return C(b);
  ),
  take(1)
);

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

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