Here它说:
// RxJS v6+
import { from } from 'rxjs';
import { groupBy, mergeMap, toArray } from 'rxjs/operators';
const people = [
{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }
];
//emit each person
const source = from(people);
//group by age
const example = source.pipe(
groupBy(person => person.age),
// return each item in group as array
mergeMap(group => group.pipe(toArray()))
);
/*
output:
[{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
[{age: 30, name: "Joe"}]
[{age: 35, name: "Sarah"}]
*/
const subscribe = example.subscribe(val => console.log(val));
在我的代码中,我不是使用'from'运算符来创建可观察对象,而是使用BehaviorSubject.asObservable()方法来创建可观察对象。
Person { name: string, age: number }
private _all: BehaviorSubject<Person[]>;
all: Observable<Person[]>;
constructor() {
this._all = new BehaviorSubject<Person[]>([]);
this.all = this._all.asObservable();
}
我可以使用异步管道遍历“全部”。但是当我尝试使用groupBy运算符时,我得到的是数组本身,而不是一一对应地包含人员:
this.all.pipe(
groupBy(
item => ... <-- here 'item' is Person[], not a Person
)
);
我在做什么错了?
答案 0 :(得分:2)
简单的答案是(不幸的)这种方式是不可能的。这是另一个post,涉及类似的问题。
您可以在这两个步骤之间达成目标:
选项1: 无订阅
// directly access the BehaviorSubject's value
const list = from(this._all.value);
this.list.pipe(
groupBy(
item => ...
)
);
选项2: 具有订阅,因为它是可观察的
// catch the plain list inside the subscription
this.all.subscribe(result => {
const list = from(result);
this.list.pipe(
groupBy(
item => ...
)
);
});