数组 – 如何使用角度2中的TypeScript过滤数组?

前端之家收集整理的这篇文章主要介绍了数组 – 如何使用角度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': '/url/vector_a' },{ 'id': 2,'name': '/url/vector_b' },{ 'id': 3,'store_id': 2,'name': '/url/vector_c' }
];

TypeScript对我来说是新的,但我认为我很接近使事情在这里工作.

(也可以覆盖原书数组,可以是一个选项,然后使用* ngFor =“#书籍簿”.)

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

//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(
    booksByAimID: Book[];
  ) {}


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

// ..omitted
您需要将代码放入ngOnInit并使用此关键字:
ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

您需要ngOnInit,因为输入存储将不会被设置到构造函数中:

ngOnInit is called right after the directive’s data-bound properties have been checked for the first time,and before any of its children have been checked. It is invoked only once when the directive is instantiated.

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

在你的代码中,图书过滤直接定义到类内容

原文链接:/angularjs/143051.html

猜你在找的Angularjs相关文章