RxJs Observable in Observable from Array
RxJs Observable in Observable from Array
我正在使用 angularfire,我得到了一个连续的数组流,其中包含任务 ID。我需要获取数组中每个 id 的任务文档作为一个新的可观察对象。然后 return 一组任务文档到流中,这样我就可以在我的组件中订阅它并显示任务列表。
到目前为止,我已经可以使用 mergeMap 了。我拆分数组并获取任务文档并将它们 return 放入流中。我的解决方案的唯一问题是,当我订阅 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 }
]
使用扫描运算符聚合
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], [])
),
)
您可以使用缓冲区运算符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]....
我正在使用 angularfire,我得到了一个连续的数组流,其中包含任务 ID。我需要获取数组中每个 id 的任务文档作为一个新的可观察对象。然后 return 一组任务文档到流中,这样我就可以在我的组件中订阅它并显示任务列表。
到目前为止,我已经可以使用 mergeMap 了。我拆分数组并获取任务文档并将它们 return 放入流中。我的解决方案的唯一问题是,当我订阅 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 }
]
使用扫描运算符聚合
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], [])
),
)
您可以使用缓冲区运算符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]....