我目前正在学习RxJS,却没有。我有以下代码:
mapOfPeople = new Map<number, any>();
const people = [
{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }
];
from(people)
.pipe(
groupBy(
person => person.age,
p => p
),
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
)
.subscribe(console.log);
这段代码来自教程。
我想将输出放入给定的哈希图中。我该如何处理?我不知道。
答案 0 :(得分:1)
在这个相当人为的示例中,您只想在最后添加一个reduce运算符:
public class TestTabsBean implements Serializable {
private String text;
public String submit() {
// cause page validation to fail
return null;
}
public String getText() {
return text;
}
public void setText(final String text) {
this.text = text;
}
}
答案 1 :(得分:0)
mapOfPeople: any;
const people = [
{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }
];
from(people)
.pipe(
groupBy(
person => person.age,
p => p
),
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
)
.subscribe(res => mapOfPeople = res /*or do whatever you want with the result*/);
有关更多信息:observable
答案 2 :(得分:0)
我无法编译您的初始代码,并且在这种情况下我不确定zip部分是什么。
一种实现方法是使用订阅函数处理程序。目前它是console.log-但您可以在此处执行(arg) => void
格式的任何操作(该函数从可观察对象中获取项目并以某种方式处理它。
下面是一个将各个年龄段的人添加到地图中的示例:
type Person = { name: string, age: number};
const mapOfPeople = new Map<number, Person[]>();
const people = [
{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }
];
from(people).pipe(
groupBy(person => person.age),
mergeMap(group => group.pipe(toArray()))
).subscribe(people => {
// the age of any in this group of people is the key
const { age } = people[0];
// set as map's value for this age
mapOfPeople.set(age, people);
});