收到错误的控制台:"无法读取属性'排序'未定义"排序和过滤时

时间:2017-08-07 07:46:26

标签: angular

我是Angular的新手,所以不要过于严格。我有一个包含所有客户列表的页面,我想要做的是按name过滤它们,然后按id排序。为了使它工作,我创建了两个pipes,一个用于过滤,另一个用于排序。 pipes中都包含appModule。他们在这里:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'filter',
  pure: false
})

export class FilterPipe implements PipeTransform {

  transform(items: any[], term): any {

    return term ? items.filter(item => item.name.indexOf(term) != -1) : items;
  }

}

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'sortBy',
  pure: false
})

export class SortPipe implements PipeTransform{

  transform(items: any[], sortedBy: string): any {
    return items.sort((a, b) => {
      return a[sortedBy] - b[sortedBy]
    })
  }

}

在视图中,我这样实现:

<input type="text" class="form-control" placeholder="Name" name="term" [(ngModel)]="term">

<table>
  <tr *ngFor="let client of clients | filter: term | sortBy: 'id'; let i = index"
    <td>{{ client.name }}</td>
  </tr>
</table>

这是我在控制台中出现的错误: enter image description here

但是在视图中一切似乎都运行正常,它过滤和排序,唯一的问题是控制台中存在错误。我怎样才能摆脱这些错误?感谢。

1 个答案:

答案 0 :(得分:0)

在执行的某个时刻,clients未定义,导致控制台出错。

您可以在调用sort方法之前通过在管道中检查它来防止这种情况。

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'sortBy',
  pure: false
})

export class SortPipe implements PipeTransform{

  transform(items: any[], sortedBy: string): any {
    if (!items) { return items; } // <-- Code to make sure the items is not undefined
    return items.sort((a, b) => {
      return a[sortedBy] - b[sortedBy]
    })
  }

}