我有一个组件和一个服务:
成分:
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);
}
}
Service:
@Injectable()
export class PersonService {
getPersons(){
var persons: Person[] = [
{id: 1, firstName:'Hans', lastName:'Mustermann', email: '[email protected] /cdn-cgi/l/email-protection', company:'Test', country:'DE'},
{id: 2, firstName:'Muster', lastName:'Mustermann', email: '[email protected] /cdn-cgi/l/email-protection', company:'test', country:'DE'},
{id:3, firstName:'Thomas', lastName:'Mustermann', email: '[email protected] /cdn-cgi/l/email-protection', company:'test', country:'DE'}
];
return persons;
}
}
我想获取具有 ID('personID')的 Person 项目。我从中获取的 personIDRouteparams
。为此我需要 foreach 循环?但我还没有找到解决这个问题的方法。
你需要使用方法Array.filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter:
this.persons = this.personService.getPersons().filter(x => x.id == this.personId)[0];
or Array.find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
this.persons = this.personService.getPersons().find(x => x.id == this.personId);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)