簡體   English   中英

如何按順序訂閱並僅返回 RxJS 中最后一個 observable 的值?

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

我在一個 Angular 路由解析器中,想要返回一個可觀察的。

我需要按順序訂閱多個異步進程:

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 之后點擊,我會得到預期的返回值。 但是我的解析器永遠不會解析? (或者發出了錯誤的東西?我真的不能說。)

如果鏈中的一個 observables 永遠不會完成(如路由參數或查詢參數),它將停止整個火車。

switchMap應該這樣做:

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

路由解析器需要在 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)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM