我想按可观察的字段对列表中的内容进行排序,但不能用可观察字段来实现这一点。有人知道如何做到这一点吗?
初始情况如下所示:
Thing[] things;
interface Thing {
name: Observable<string>
}
<ul>
<li *ngFor="const thing for things">
{{thing.name | async}}
</li>
</ul>
因为我显然没有正确地描述我的问题:我想要对列表中的内容进行排序的字段是一个可观察的,而不是一个普通的字符串。我希望通过websockets保持字段的更新,因此为了正确检测更改,我必须使用可订阅的可观察字段。
发布于 2017-02-15 20:26:38
谢谢你澄清了这个问题,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" }
]
如果您对此代码有任何疑问,请与我联系。
发布于 2017-02-13 20:29:40
您可以使用Observable.map
。例如:
Observable<Thing[]> things;
sortedThings$ = things.map(items => items.sort()) // Use your own sort function here.
在您的模板中:
<ul>
<li *ngFor="let thing of sortedThings$ | async">
{{thing.name}} <!--No need async pipe here. -->
</li>
</ul>
发布于 2018-07-11 23:30:48
您可以在localeCompare
中使用Observable.map
,然后使用sort()
,如下所示:
.map(data => ({
label: data.name
}))
.sort((a, b) => a.label.localeCompare(b.label));
https://stackoverflow.com/questions/42203953
复制相似问题