Angular2 rxjs通过可观察字段对对象列表进行排序(可观察) [英] Angular2 rxjs sort (observable) list of objects by an observable field
问题描述
我想按可观察字段对事物列表进行排序,但无法将头围在可观察对象周围以使此工作正常进行.有人知道如何实现这一目标吗?
I want to sort a list of things by an observable field, but can't wrap my head around observables to get this working. Has somebody an idea how to achieve this?
初始情况如下:
Thing[] things;
interface Thing {
name: Observable<string>
}
<ul>
<li *ngFor="const thing for things">
{{thing.name | async}}
</li>
</ul>
由于我显然没有正确地描述我的问题:我想要对事物列表进行排序的字段是一个Observable,而不是纯字符串.我想通过websockets来更新该字段,以便正确检测更改,我必须使用可以订阅的Observable字段.
Since I obviously haven't described my problem properly: The field I want to sort the list of things on is an Observable, not a plain string. I want to keep the field updated via websockets so to detect the changes properly I have to use an Observable field on which I can subscribe.
推荐答案
感谢您澄清问题磷". :)
Thanks for clarifying the question, Phosphoros. :)
这是您可以按照要求执行的操作:
Here's how you could do what you asked:
// Function to compare two objects by comparing their `unwrappedName` property.
const compareFn = (a, b) => {
if (a.unwrappedName < b.unwrappedName)
return -1;
if (a.unwrappedName > b.unwrappedName)
return 1;
return 0;
};
// Array of Thing objects wrapped in an observable.
// NB. The `thing.name` property is itself an observable.
const thingsObs = Observable.from([
{ id: 1, name: Observable.of('foo') },
{ id: 2, name: Observable.of('bar') },
{ id: 3, name: Observable.of('jazz') }
]);
// Now transform and subscribe to the observable.
thingsObs
// Unwrap `thing.name` for each object and store it under `thing.unwrappedName`.
.mergeMap(thing =>
thing.name.map(unwrappedName => Object.assign(thing, {unwrappedName: unwrappedName}))
)
// Gather all things in a SINGLE array to sort them.
.toArray()
// Sort the array of things by `unwrappedName`.
.map(things => things.sort(compareFn))
.subscribe();
将发出的值记录到控制台将显示Thing对象的数组,这些对象按其unwrappedName
属性排序:
Logging emitted values to the console will show an array of Thing objects sorted by their unwrappedName
property:
[
{ id: 2, name: ScalarObservable, unwrappedName: "bar" },
{ id: 1, name: ScalarObservable, unwrappedName: "foo" },
{ id: 3, name: ScalarObservable, unwrappedName: "jazz" }
]
如果您对此代码有疑问,请告诉我.
Please let me know if you have questions about this code.
这篇关于Angular2 rxjs通过可观察字段对对象列表进行排序(可观察)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!