如何在 Angular 2 中使用 TypeScript 过滤数组?

新手上路,请多包涵

ng-2 父子数据继承对我来说一直是个难题。

看起来可能是一个很好的实用解决方案是将我的总数据数组过滤为一个数组,该数组仅由单个父 ID 引用的子数据组成。换句话说:数据继承变成了一个父ID的数据过滤。

在一个具体的例子中,这看起来像:过滤一个书籍数组以仅显示具有特定 store_id 的书籍。

 import {Component, Input} from 'angular2/core';

export class Store {
  id: number;
  name: string;
}

export class Book {
  id: number;
  shop_id: number;
  title: string;
}

@Component({
  selector: 'book',
  template:`
    <p>These books should have a label of the shop: {{shop.id}}:</p>

    <p *ngFor="#book of booksByShopID">{{book.title}}</p>
  `
])
export class BookComponent {
  @Input()
  store: Store;

  public books = BOOKS;

  // "Error: books is not defined"
  // ( also doesn't work when books.filter is called like: this.books.filter
  // "Error: Cannot read property 'filter' of undefined" )
  var booksByStoreID = books.filter(book => book.store_id === this.store.id)
}

var BOOKS: Book[] = [
  { 'id': 1, 'store_id': 1, 'name': 'Dichtertje' },
  { 'id': 2, 'store_id': 1, 'name': 'De uitvreter' },
  { 'id': 3, 'store_id': 2, 'name': 'Titaantjes' }
];

TypeScript 对我来说是新的,但我认为我已经接近让事情在这里工作了。

(也可以选择覆盖原始书籍数组,然后使用 *ngFor="#book of books" 。)

编辑 越来越近,但仍然给出错误。

 //changes on top:
import {Component, Input, OnInit} from 'angular2/core';

// ..omitted

//changed component:
export class BookComponent implements OnInit {
  @Input()
  store: Store;

  public books = BOOKS;

  // adding the data in a constructor needed for ngInit
  // "EXCEPTION: No provider for Array!"
  constructor(
    booksByStoreID: Book[];
  ) {}

  ngOnInit() {
    this.booksByStoreID = this.books.filter(
      book => book.store_id === this.store.id);
  }
}

// ..omitted

原文由 Code-MonKy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 861
1 个回答

您需要将代码放入 ngOnInit 并使用 this 关键字:

 ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

您需要 ngOnInit 因为输入 store 不会设置到构造函数中:

ngOnInit 在第一次检查指令的数据绑定属性之后,并且在检查其任何子项之前立即调用。当指令被实例化时,它只被调用一次。

https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html

在您的代码中,书籍过滤直接定义到类内容中……

原文由 Thierry Templier 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进