我有这一系列的候选人。其中一些被删除,其中一些不是。它们是无序的,我想按姓氏和它们是否被删除来命令它们。我使用的管道只接受数组,如果元素是对象,则按给定属性对它们进行排序。
这并不困难:
let added = this.candidates.filter(c => !c.removed);
let removed = this.candidates.filter(c => c.removed);
added = new OrderByPipe().transform(added, ['lastName']);
removed = new OrderByPipe().transform(removed, ['lastName']);
let orderedCandidates = added.concat(removed);
为了我自己的兴趣,我想将我的候选数组转换为一个可观察的数据并将其传递给.partition()
到目前为止,我一直在管理:
orderCandidates() {
let [added, removed] = Observable.from(this.candidates)
.partition(c => !c.removed);
added = added.toArray().map(a => new OrderByPipe().transfrom(a, ['-lastName']));
removed = removed.toArray().map(r => new OrderByPipe().transfrom(r, ['-lastName']));
}
然后我想将两个已排序的数组压缩或连接成一个新数组。我最近了解到,我在脑海里想到了rxjs中流经一个非常简化的管道的所有内容,我觉得当我尝试遵循这个图像时,我的想法就用完了。
答案 0 :(得分:0)
实际上,如果您的orderedCandidates
已经过滤了 AND 排序数组,为什么不使用Observable.of()
从中创建一个observable?:
let added = this.candidates.filter(c => !c.removed);
let removed = this.candidates.filter(c => c.removed);
added = new OrderByPipe().transform(added, ['lastName']);
removed = new OrderByPipe().transform(removed, ['lastName']);
let orderedCandidates = added.concat(removed);
//create an Observable of list of ordered, sorted candidates
let orderedCandidates$ = Observable.of(orderedCandidates);
或者,如果你真的爱上了Observable并希望只使用Observable操作符,那么只需使用.map()
来转换你的数据:
orderCandidates() {
let orderedCandidate$ = Observable.from(this.candidates)
.partition(c => !c.removed)
.map(([added, removed])=>{
added = added.toArray().map(a => new OrderByPipe().transfrom(a, ['-lastName']));
removed = removed.toArray().map(r => new OrderByPipe().transfrom(r, ['-lastName']));
return added.concat(removed);
})
return orderedCandidate$;
}