首页 > 解决方案 > Angular 6中的数组排序不正确

问题描述

我正在使用 *ngFor 来迭代数据表中的对象数组和序列号。我使用let index of i然后将其打印到桌子上,但我面临的问题是在第 9 个序列号之后。我有 10 个,但在 1 个序列号之后。像 1, 10, 11, 2, 3。有人能帮我吗?这是我的打字稿代码和 html 代码。 这是屏幕截图

// GETTING BONUS DATA
 getAllJobposts() {
 this.apiService.hrService.getAllJobPost().subscribe((res: any) => {
  this.jobPostsData = res.data;
  console.log(this.jobPostsData);
  // this.DataTablesFunctionCallAfterDataInit()
 });
}

 <tr class="MousePointer" (click)="EditRecord(post.id, target)" *ngFor="let 
   post of jobPostsData | reverse; let i = index">

              <td>{{ i+1 }}</td>
              <td>
                <span style="display: inline">
                  <a class=" btn btn-link btn-sm " title="Delete" [id]="post.id" (click)="$event.stopPropagation();modal.ShowModal(post.id)">
                    <i [ngStyle]="{color: 'blue'}" class="fa fa-trash-o ">
                    </i>
                  </a>
                  <a class="btn btn-link btn-sm btn-round" title="Edit" (click)="$event.stopPropagation();EditRecord(post.id,target)">
                    <i [ngStyle]="{color: 'blue'}" class="fa fa-pencil-square-o "></i>
                  </a>
                </span>
              </td>
              <td>{{ post.jobTitle }}</td>
              <td>{{ getDepartmentName(post.departmentId) }}</td>
              <td>{{ getDesignationName(post.designationId) }}</td>
              <td>{{ post.totalPosition }}</td>
              <td>{{ post.minExperience }}</td>
              <td>{{ getCityName(post.cityId) }}</td>
              <td>
                <span [class]="post.active == 1? 'status success':'status danger'" style="width:60px !important; text-align: center;">
                  {{post.active == 1? "Active":"In-Active" }}
                </span>
              </td>
            </tr>

标签: angularhtml-tablengforhttpservice

解决方案


似乎您需要通过以下方式重写您的reverse管道:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value) {
    return value.sort((a, b) => {
      return (b.id - a.id);
    }); 
  }
}

在排序功能中,您需要指定用于排序的对象字段: return (b.id - a.id).

或者parseInt(b.id) - parseInt(a.id)如果 id 是字符串则使用(否则它将输出与屏幕截图相同的结果,即按字母顺序)

此外,您可以通过管道参数传递对象字段进行排序


推荐阅读