加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:46:06 所属栏目:安全 来源:网络整理
导读:ng-2亲子数据继承对我而言是一个困难. 什么似乎是一个很好的工作实际的解决方案是将我的总数据数据过滤到仅由单个父ID引用的子数据组成的数组. 换句话说:数据继承成为一个父ID的数据过滤. 在一个具体的例子中,这可以看起来像:过滤一个书籍数组,只显示具有
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)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读