【问题标题】:(Angular2) `*ngfor` doesn't work with filter using pipe from async data(Angular2) `*ngfor` 不适用于使用来自异步数据的管道的过滤器
【发布时间】:2017-07-02 23:22:50
【问题描述】:

我有如下简单的 Angular 2 应用程序:

数据结构

class Item {
  name: string,
  status: boolean
}

模板

<ul *ngIf="items">
  <li *ngFor="let item of items">{{ item.name }}</li>
</ul>

组件

export class ItemsComponent implement OnInit {

  items: Item[]

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.getItems();
  }

  private getItems(): void {
    this.itemService.getItems().then(items => this.items = items);
  }

}

使用ItemService 的异步数据接收器getItems() 使用Promise

这个应用程序很好用。完整的项目列表显示在浏览器上。


我只想显示状态为true 的项目。为此,我实现了一个简单的管道,通过status 过滤items

@Pipe({
  name: 'filterByStatus'
})
export class FilterByStatusPipe implements PipeTransform {

  transform(votes: Vote[], status: boolean): Vote[] {
    return votes.filter(vote => vote.status === status);
  }
}

我将模板中的li 标记更新为

<li *ngFor="let item of items|filterByStatus:true">{{ item.name }}</li>

但是,此更新使 &lt;ul *ngIf="items"&gt; 为 false,因此不会计算 &lt;li&gt;s。 (即items === undefined

我不知道为什么第一个版本运行良好,但更新版本却不行。我怎样才能得到itemsstatus === true

谢谢。

【问题讨论】:

  • 您的代码实际上是正确的,应该可以正常工作。您有多确定 vote.status 实际上是用布尔值填充的?管道使items 未定义也是没有意义的。还有其他问题

标签: javascript angular


【解决方案1】:

每个人都应该知道:

不要使用status 作为属性或变量的名称。它可能会在您的环境中使用。

看到这个:JS reserved keywords list


重命名可以解决问题。

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2019-04-11
    • 2016-02-18
    • 2017-05-15
    • 2017-05-04
    相关资源
    最近更新 更多