rxjs減少不繼續 (rxjs reduce does not continue)


問題描述

rxjs減少不繼續 (rxjs reduce does not continue)

我在 Angular 7 應用程序中有以下設置:

@Effect({dispatch:false})
LoadInstances$ = this.actions$.pipe(
ofType(fromAppAction.AppActionTypes.LoadInstances),
take(1), // <‑‑ solved my problem
switchMap((action: fromAppAction.LoadInstances) =>
      this.entityService.GetInstances()
    ),

switchMap(instances=>from(instances)), // flatten the array to single values
flatMap( // combine the instance with its UserData
    (inst)=>this.entityService.GetCurrentUserInfo().pipe(take(1)),
    (inst,usr)=>({...inst, UserData:usr})
),
flatMap(
  (inst)=>this.entityService.GetUserPersonalSettings(inst.id).pipe(take(1)),
  (inst,settings)=>({...inst, Settings:settings})
),
tap(result=>console.log('before reduce:',result)), // <‑‑ this gets called 3 times (I have 3 instances)
reduce<Instance>((a, c) => [...a, c], []), // accumulate all results to one array
tap(result=>console.log('instances: ', result)), // <‑‑ this gets never called
...

本質上,我有一個實例數組,將它們展平,為每個實例調用 GetCurrentUserInfo 和 GetUserPersonalSettings,將結果添加為屬性到實例,然後想將它們累積回 Instance[]。

到目前為止,這有效,只是 reduce 函數不會繼續。我知道這是因為其他 observables 之一沒有完成。但怎麼可能呢?最初的 from(instances) 遍歷數組,然後應該完成,是嗎?並且對 GetPersonalSettings 的調用只是簡單的 httpClient.get() 調用,根據文檔,它是在成功調用後完成的單值可觀察對象。

有人可以幫助我嗎?

[編輯] 掃描在這裡不是一個選項,因為我需要完整的實例數組才能繼續。[Edit2] toArray 和 reduce 有同樣的問題,它只會在前一個 Observable(s?) 完成時才發出結果。

無論如何:我不想改變這個設置因為它基本上可以工作。我只想了解哪個 Observable 沒有完成以及為什麼。這將解決我的問題。


參考解法

方法 1:

Recently I learned about operator toArray, might simplify your code. You stream doesn't complete because stream before first switchMap is not completed

/* What is here? Probably still open stream? */
switchMap((action: fromAppAction.LoadInstances) =>
  this.entityService.GetInstances()
),

Quick try would be put first() or take(1) before first switchMap

(by joachim_bMaksim Romanenko)

參考文件

  1. rxjs reduce does not continue (CC BY‑SA 2.5/3.0/4.0)

#ngrx-effects #Angular #rxjs






相關問題

rxjs減少不繼續 (rxjs reduce does not continue)

從 reducer/action 觸發 API 重新加載的正確方法是什麼? (What's the proper way to trigger the API reload from reducer/action?)

Angular NgRx 效果,如何傳遞參數? (Angular NgRx effects, how to pass a parameter?)

NgRx 效果無限循環 (NgRx Effects infinite loop)

發送 forkjoin api,每個 api 之間有延遲 (Send forkjoin api with a delay in between each api)

如何從所有待處理的請求中取消特定請求 (How to cancel specific request from all pending request)

使用 NgRx 存儲優化 Angular 內存以避免內存洩漏 (Angular memory optimization with NgRx store to avoid memory leaks)

NgRx EffectsModule 導入組 (NgRx EffectsModule imports group)

切換地圖後在NGRX特效點擊功能中獲取動作道具 (Get action props in the NGRX effects tap function after switch Map)

如何防止在 NgRx 中第二次加載數據? (How prevent loading data second time in NgRx?)

需要幫助了解這種 Ngrx 效果 (Need help understanding this Ngrx effect)

測試效果 NgRx Angular 11 (Testing effects NgRx Angular 11)







留言討論