gpt4 book ai didi

angular - RxJS 6 过滤并映射一个可观察的项目数组

转载 作者:行者123 更新时间:2023-12-01 08:22:06 25 4
gpt4 key购买 nike

在我使用 RxJS 6.3.3 的 Angular 7.1.1 应用程序中,一个可观察的计划数组应该转换为一个可观察的事件计划卡数组。有源滤波器是:

filter(plan => plan.is_active)

计划到卡的转化为:
map(plan => new PlanCard(plan, 1, 1))

所以,想必,答案是这样的:
plans: Observable<Plan[]> = getPlans();

cards: Observable<PlanCard[]> = plans.pipe(
mergeAll(),
filter(plan => plan.is_active),
map(plan => new PlanCard(plan, 1, 1)),
toArray()
);

但唉, cards是空的。

计划可以通过以下方式正确转换为卡片:
cards: Observable<PlanCard[]> = plans.pipe(
map(plans => plans.map(plan => new PlanCard(plan, 1, 1)))
);

但不幸的是,添加过滤器之前不会过滤计划:
cards: Observable<PlanCard[]> = plans.pipe(
filter(plans => plans.filter(plan => plan.is_active)),
map(plans => plans.map(plan => new PlanCard(plan, 1, 1)))
);

有什么更好的想法吗?
export const planData: Plan[] = [{
name: 'P1',
is_active: true
}, {
name: 'P2',
is_active: true
}, {
name: 'P3',
is_active: true
}, {
name: 'P4',
is_active: true
}, {
name: 'P5',
is_active: false
}];

export const plans = createObservable(planData);

最佳答案

mergeAll 合并一个 observable 的 observable。

你要

cards: Observable<PlanCard[]> = plans.pipe(
map(plans => plans.filter(plan => plan.is_active)), // An array comes down the pipe, you don't want to filter out the arrays but the elements in the array
map(plans => plans.map(plan => new PlanCard(plan, 1, 1))), // An array of active plans can be mapped into an array of PlanCards
reduce((results, plans) => [...results, ...plans], []) // Reduce all the arrays into a single array
);

如果您希望每次新数组下降时都让 reduce 的累加器沿管道下降,则可以使用 scan 而不是 reduce,reduce 仅在所有数组下降到管道后才触发。

我通常不使用过滤器后跟 map ,但更容易看到发生了什么,我通常会在一个步骤中使用reduce来完成,
plans => plans.reduce((results, plan) => plan.is_active ? [...results, new PlanCard(plan, 1, 1)] : results, [])

与后跟 map 的过滤器相同,但在单次迭代中执行,而不是两次。

当您拥有数组的 observable 时,这可能会非常令人困惑,您需要考虑要将哪些函数应用于 observable,以及要将哪些函数应用于管道中的数组。

const { from } = rxjs;
const { map, reduce } = rxjs.operators;

const plans = from([
[{id: 1, is_active: true}, {id: 2, is_active: false}, {id: 3, is_active: true}, {id: 4, is_active: true}],
[{id: 5, is_active: true}, {id: 6, is_active: true}],
[{id: 7, is_active: false}, {id: 8, is_active: true}, {id: 9, is_active: true}],
[{id: 10, is_active: true}, {id: 11, is_active: false}, {id: 12, is_active: true}, {id: 13, is_active: false}],
]);

function PlanCard(plan) {
this.id = plan.id;
}

plans.pipe(
map(plans => plans.reduce((results, plan) => plan.is_active ? [...results, new PlanCard(plan, 1, 1)] : results, [])),
reduce((results, plans) => [...results, ...plans], [])
).subscribe(results => { console.log(results); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script>

关于angular - RxJS 6 过滤并映射一个可观察的项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53660882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com