【问题标题】:Angular sort by json property with Angular Material md-select使用 Angular Material md-select 按 json 属性进行 Angular 排序
【发布时间】:2018-01-21 17:22:17
【问题描述】:

不确定如何使用 md-select 对返回的 json 数据列表进行排序。我需要一根管子吗?还是只是我组件中的一个函数?

返回的 json 对象

[ { name: 'repo-name', created_at: '2017-1-15T10:30:37Z', updated_at: '2017-1-16T11:30:30Z'}, {...} ]

repos.component.html

<!-- select with function if needed -->
<md-select placeholder="Sort by">
    <md-option *ngFor="let sort of sorts" [value]="sort.value"
      (click)="sortRepos( sort.value )">
      {{ sort.viewValue }}
    </md-option>
</md-select>

<!-- repeater -->
<md-list-item *ngFor="let repo of repos ">...</md-list-item>

repos.component.ts

export class ReposComponent implements OnInit, OnChanges  {
    repos: any[] = []; // populated via API call
    errorMessage: string;
    sorts: any[] = []; // for select options in constructor
    sortBy = 'created_at'; // set default sortBy

    constructor(private _repoService: ReposService ) {
        this.sorts = [
            { viewValue: 'newest', value: 'created_at' },
            { viewValue: 'updated', value: 'updated_at' },
            { viewValue: 'alphabetical', value: 'name' },
        ];
    }

    sortRepos( value ) {
        // ??? fails, doesn't seem like the right approach
        this.sortBy = value;
        this.sortBy === 'name' ? this.repos.sort( repo => repo.name )
        : this.sortBy === 'created_at' ? this.repos.sort( repo => repo.created_at )
        : this.repos.sort( repo => repo.updated_at );
    }

    ngOnInit() {
        this._repoService.getRepos()
           .subscribe( repos => { this.repos = repos; 
           console.log(repos); },error => this.errorMessage = <any>error );
    }

    ngOnChanges() {}
}

我在正确的轨道上吗?还是我需要一个能以某种方式进入 .name、.created_at 和 .updated_at 并根据它进行排序的管道?

谢谢!

【问题讨论】:

  • 您在正确的轨道上,但我会按照@Lazar 的建议考虑使用 Lodash。我认为您不需要管道。我注意到的是,您没有将排序后的数组分配回代码中的任何位置的 repos 数组。对this.repos.sort() 的调用会返回一个新数组——它不会更改现有数组。您应该使用this.repos = this.repos.sort(...) 以使排序生效。

标签: angular sorting select drop-down-menu angular-material2


【解决方案1】:

您可以创建自定义管道或仅在组件中编写逻辑。使用 JavaScript 中的 Array#sort 函数。 Angular 在这里并没有什么特别之处,它只是你自定义的数据转换。

排序函数接受一个应该返回的比较函数。 1、0 或 -1 基于比较结果。此函数的两个参数是要比较的数组的两项。

您当前传递的参数适用于 sortBy function from Lodash,因此您可能有兴趣使用它而不是原版解决方案。

Array#sort

const sortedArr = arr.sort((a, b) => a.name > b.name ? 1 : -1)

_.sortBy

const sortedArr = _.sortBy(arr, x => x.name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多