Angular 2 TypeScript 如何在数组中查找元素 [英] Angular 2 TypeScript how to find element in Array

查看:46
本文介绍了Angular 2 TypeScript 如何在数组中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件和一个服务:

I have a Component and a Service:

组件:

export class WebUserProfileViewComponent {
    persons: Person [];
    personId: number;
    constructor( params: RouteParams, private personService: PersonService) {
          
        
           this.personId = params.get('id');
           this.persons =  this. personService.getPersons();
           console.log(this.personId);  
        }
}

服务:

@Injectable()
export class PersonService {
      getPersons(){
        var persons: Person[] = [
            {id: 1, firstName:'Hans', lastName:'Mustermann', email: 'mustermann@test.com', company:'Test', country:'DE'},
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: 'mustermann@test.com', company:'test', country:'DE'},
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: 'mustermannt@tesrt.com', company:'test', country:'DE'}
        ];
          
        return persons;
      }
}

我想获取带有 Id ('personID') 的 Person Item.我从 Routeparam 获得的 personID.为此,我需要 foreach 循环?但我还没有找到解决方案.

I want to get the Person Item with the Id ('personID'). The personID i get from Routeparam. For that I need the foreach loop? But I haven´t found a solution for this.

推荐答案

您需要使用方法 Array.filter:

You need to use method Array.filter:

this.persons =  this.personService.getPersons().filter(x => x.id == this.personId)[0];

Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);

这篇关于Angular 2 TypeScript 如何在数组中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆