我有以下代码段:
static groupAlphabetically<T>(observable:Observable<T[]>): Observable<AlphabeticalGroup<T>[]>{
return (observable.pipe(
switchMap(data => data as T[]),
reduce((r, e:T) => {
let group = e["name"][0] as string;
var currentGroup = r.filter(x => x.letter == group)[0];
if(!currentGroup)
{
currentGroup = new AlphabeticalGroup<T>();
currentGroup.letter = group;
r.push(currentGroup);
}
currentGroup.items.push(e);
return r;
}, new Array<AlphabeticalGroup<T>>())
));
}
由于某种原因,此管道可观察对象永远不会结束。 我究竟做错了什么? 调试时,我可以使用return r语句,但是订阅永远行不通:
subscribe(x => {
// this code is never reached
})
答案 0 :(得分:0)
switchMap不会扩展Array,因此在化简函数e!= T但e = T []中。 在RxJS中使用groupBy运算符。
请参见下面的example
export const groupAlphabetical = (observable: Observable<hasName[]>) => observable.pipe(
flatMap(x => x),
groupBy(x => x.name[0],x=> x),
mergeMap( (group$) => group$.pipe(reduce((acc, cur) =>{
acc.items = [...acc.items, cur];
return acc;
}, {
letter: group$.key,
items:[]
})))
);
hasName接口:
export interface hasName {
name: string;
}