我想按可观察字段对事物列表进行排序,但无法全神贯注于可观察对象以使其正常工作。有人知道如何实现这一目标吗?
初始情况是这样的:
Thing[] things;
interface Thing {
name: Observable<string>
}
<ul>
<li *ngFor="const thing for things">
{{thing.name | async}}
</li>
</ul>
因为我显然没有正确描述我的问题:我想要对事物列表进行排序的字段是一个 Observable,而不是一个纯字符串。我想通过 websockets 保持字段更新,以便正确检测更改我必须使用我可以订阅的 Observable 字段。
最佳答案
感谢您澄清问题,Phosphoros。 :)
这里是你如何做你所要求的:
// 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();
将发出的值记录到控制台将显示一组按其 unwrappedName
属性排序的 Thing 对象:
[
{ id: 2, name: ScalarObservable, unwrappedName: "bar" },
{ id: 1, name: ScalarObservable, unwrappedName: "foo" },
{ id: 3, name: ScalarObservable, unwrappedName: "jazz" }
]
如果您对此代码有任何疑问,请告诉我。
关于Angular2 rxjs 按可观察字段对对象列表进行排序(可观察),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42203953/