簡體   English   中英

來自數組的 Observable 中的 RxJs Observable

[英]RxJs Observable in Observable from Array

我正在使用 angularfire 並且我得到了包含任務 ID 的連續數組流。 我需要獲取數組中每個 id 的任務文檔作為新的 observable。 然后將一系列任務文檔返回到流中,以便我能夠在我的組件中訂閱它並顯示任務列表。

到目前為止,我讓它與mergeMap一起工作。 我拆分數組並獲取任務文檔並將它們返回到流中。 我的解決方案的唯一問題是,當我訂閱 Observable 時,我沒有得到一系列任務,但每個任務都是一個單一的更改,我無法使用 ngFor 循環。 使用 toArray() 運算符在這種情況下不起作用,因為它是一個永不結束的連續流。

到目前為止,這是我的代碼:

this.db.collection(`games/${gameId}/missions`).valueChanges().pipe(
    mergeMap(missions => missions),
    mergeMap((mission: any) => {
        return this.db.doc(`missions/${mission.id}`).snapshotChanges();              
    }),
);

這會在單個事件中生成以下輸出:

{ id: 1, missionProperties }
{ id: 2, missionProperties }
{ id: 3, missionProperties }

但我想在一個事件中將它作為一系列任務:

[
    { id: 1, missionProperties },
    { id: 2, missionProperties },
    { id: 3, missionProperties }
]

您可以使用緩沖區運算符https://www.learnrxjs.io/operators/transformation/buffer.html

of(1, 2, 3, 4, 5).pipe(
  bufferCount(5),
).subscribe(x => console.log(x)); // prints [1, 2, 3, 4, 5]

編輯:

我剛剛看到了 toArray() 運算符:

of(1, 2, 3, 4, 5).pipe(
  toArray(),
).subscribe(x => console.log(x));

編輯 2:

of(1, 2, 3, 4, 5).pipe(
  scan((acc, curr) => { acc.push(curr); return acc; }, []),
).subscribe(x => console.log(x)); // prints [1] [1,2] [1,2,3]....

使用掃描運算符聚合

this.db.collection(`games/${gameId}/missions`).valueChanges().pipe(
  switchMap(missions =>
      from(missions).pipe(
        mergeMap(mission => this.db.doc(`missions/${mission.id}`).snapshotChanges()),
       scan((acc, curr) => [curr, ...acc], [])
      ),
)

暫無
暫無

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

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