1

我在一个 Angular 路由解析器中,想要返回一个 observable。

我需要按顺序订阅多个异步进程:

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

C 依赖于 B,B 依赖于 A。A 必须完成,然后是 B,然后是 C,但我只希望 C 中的值用于导致路由解析。

我尝试了两种不同的方法:

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

我也试过

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

我如何订阅 A,然后是 B,然后是 C ...,然后只从最里面的 observable 中获取值?

如果我在最后一个 concatMap 之后点击,我会得到预期的返回值。但是我的解析器永远不会解析?(或者发出了错误的东西?我真的不能说。)

4

2 回答 2

2

路由解析器需要在 Angular 路由器继续运行之前完成。路线守卫也是如此。添加一个接受发射的运算符,例如 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)
);
于 2019-10-19T00:56:13.657 回答
2

如果链中的一个 observable 永远不会完成(如路由参数或查询参数),它将停止整个火车。

switchMap应该做:

A.pipe(
    switchMap(B), // which is more or less the same as `switchMap(a => B(a))`
    switchMap(C),
).subscribe(//...
于 2019-10-18T21:59:06.043 回答