gpt4 book ai didi

Angular 2 TypeScript如何在数组中查找元素

转载 作者:太空狗 更新时间:2023-10-29 16:45:11 25 4
gpt4 key购买 nike

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

组件:

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 项。我从 Routeparams 获得的 personID。为此我需要 foreach 循环?但我还没有找到解决方案。

最佳答案

你需要使用方法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如何在数组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37969984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com