简体   繁体   English

如何使用排序选项?

[英]How to use SORT options?

I take data from ngrx-store我从ngrx-store获取数据

getData$: Observable<IGetData>;

this.getData$ = this.store.select(
      fromStore.dataSelector.getNewData,
    );

// array example [
{id: number, name: string, btn: number, index: number},
{id: number, name: string, btn: number, index: number},
{id: number, name: string, btn: number, index: number}
]

And in HTML I use this in *ngFor在 HTML 我在*ngFor中使用它

<div *ngFor="let data of getData$ | async">
  <div>{{data.name}}</div>
</div>

I want to orderby this by ID direct in component because orderBy PIPE directly in view is not recommendation.我想通过ID直接在组件中PIPE orderby在视图中不推荐。

I try this but I get error Property 'sort' does not exist on type我试试这个,但我得到错误Property 'sort' does not exist on type

// descending
this.getData$.sort((a, b) => b.id - a.id); 

//ascending
this.getData$.sort((a, b) => a.id - b.id);

How to use in this case SORT options?在这种情况下如何使用SORT选项?

Thnx谢谢

I don't use angular, so I'm not sure of the answer.我不使用angular,所以我不确定答案。 But it looks like your data is not array.但看起来您的数据不是数组。 I had similar issue with some data from MongoDB where even it was an array it was passed as an object.我对来自 MongoDB 的一些数据有类似的问题,即使它是一个数组,它也被作为 object 传递。 You can try wrapping data in Array.from() like Array.from(this.getData$).sort((a, b) => a.id - b.id)您可以尝试将数据包装在Array.from()中,例如Array.from(this.getData$).sort((a, b) => a.id - b.id)

You can also verify the type of data to make sure it's an array.您还可以验证数据的类型以确保它是一个数组。 console.log((typeof((a, b) => a.id - b.id))

Take a look at this ngrx effets .看看这个ngrx effets Since your getData$ is an Observable and not an Array you can try something like this:由于您的getData$Observable而不是Array您可以尝试这样的事情:

this.getData$ = this.getData$
  .pipe(
     map((data) => data.sort((a,b) => a.id - b.id))
  );

Although I have never worked with ngrx, I have found something in the docs for manipulating (sorting your entities) the proper way ( ngrx adapter ).虽然我从未使用过ngrx,但我在文档中找到了一些以正确方式( ngrx 适配器)操作(对您的实体进行排序)的东西。

I don't know where did you see that PIPE is not recommended.不知道你在哪里看到不推荐的PIPE But in your case, you can: Use an Angular pipe, or modify your Observable like this:但在您的情况下,您可以:使用 Angular pipe,或者像这样修改您的 Observable:

this.getData$ = this.store.pipe(
  select(fromStore.dataSelector.getNewData),
  map(data => [...data].sort((a, b) => b.id - a.id)),
);

sort modify the array, so you should make a copy of it with [...data] sort修改数组,所以你应该用[...data]复制它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM