Angular2 rxjs 按可观察字段排序(可观察)对象列表 [英] Angular2 rxjs sort (observable) list of objects by an observable field

查看:21
本文介绍了Angular2 rxjs 按可观察字段排序(可观察)对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按可观察字段对事物列表进行排序,但无法围绕可观察对象进行排序以使其正常工作.有人知道如何实现这一目标吗?

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.

推荐答案

感谢您澄清问题,Phosphoros.:)

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();

将发出的值记录到控制台将显示一组按其 unwrappedName 属性排序的 Thing 对象:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆