Angular 6使用键/属性获取列表中的对象列表

时间:2018-07-29 20:35:49

标签: angular typescript

Entity1Service.ts 中的 getEntities()方法返回以下错误。

Type 'Entity1' is not assignable to type 'Entity1[]'. Property 'includes' is missing in type 'Entity1'

获取包含与另一个实体相关联的ID号的对象列表的正确方法是什么?该应用程序使用的是Angular 6。

Entity1.ts

export class Entity1 {
    id: number;
    name: string;
    entitiy2Id: number;

    constructor(
        _id: number,
        _name: string,
        _entity2Id: number
    ) {
        this.id = _id,
        this.name = _name
        this.entity2Id = _entity2Id
    }
}

Entity2.ts

export class Entity2 {
    id: number;
    name: string;

    constructor(
        _id: number,
        _name: string
    ) {
        this.id = _id;
        this.name = _name;
    }
}

Entity1Service.ts

import { Injectable } from '@angular/core';
import { Entity1 } from './models/entity1';

@Injectable({
  providedIn: 'root'
})
export class Entity1Service {

  entities: Enity1[] = [
    { 
      id: 1,
      name: 'First',
      entity2Id: 1 
    },
    { 
      id: 2,
      name: 'Second',
      entity2Id: 1 
    },
    { 
      id: 3,
      name: 'Third',
      entity2Id: 1 
    }
  ];

  constructor() { }

  getEntities(_entity2Id: number): Entity1[] {
    // The following line does not work
    return this.entities.find(entity => entity.entity2Id === _entity2Id);
  }

}

1 个答案:

答案 0 :(得分:2)

find() 将仅返回1个匹配元素,请改用 filter() ,因为您的方法需要返回 {{1} }

[]