我有一个BehaviourSubject
,可以解析为一个集合,其中的每个项目都具有一个属性children
,它也是一个BehaviourSubject
,可以解析为一个项目集合。现在,我想订阅我的主题,并将整个内容整理成一个数组,其中每个项目和每个孩子都有一行。
所以在以下行中:
interface Parent = {
children: BehaviorSubject<Child[]>
}
现在,我想以此为基础制定另一个行为主题,该行为分解为一个数组,在该数组中,每个父项都有一个项,后跟其子项。
开始于:
const collection: BehaviorSubject<Parent[]>;
想要得到:
const behaviourSubject: BehaviorSubject<Parent|Child[]>;
behaviourSubject.subscribe((result: (Parent|Child)[]) => {
...desired result...
});
因此,假设集合中的第一个Parent
有3个子代,而第二个有2个子代,那么如果我订阅结果behaviourSubject
,则输出应如下所示。
result: [Parent, Child, Child, Child, Parent, Child, Child];
我该如何实现。
我试图通过阅读RxJS文档并查看示例来弄清楚该如何做,但是我想最近的睡眠不足似乎使我的大脑像一块干海绵一样工作,我认为现在最好的方法是在StackOverflow上寻求帮助。
Note:如果父集合或子集合获得新值,则结果也应更新...
如下所示,但我不知道为什么您使用BehaviorSubject来增加复杂性
const parent1={children:new BehaviorSubject([{name:'john'},{name:'may'},{name:'betty'}])}
const parent2={children:new BehaviorSubject([{name:'key'},{name:'tom'}])}
const collection=new BehaviorSubject([parent1,parent2]);
collection.pipe(
first(),
switchMap(parent=>from(parent)),
switchMap(p=>p.children.pipe(first(),map(c=>[p,...c]))),
toArray(),
map(arr=>arr.flat())
).subscribe(console.log)
如果您不介意使用BehaviourSubject的.value属性,则代码可以减少到下面]
collection.value.map(p=>[p,...p.children.value]).flat()