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

标签 angular typescript angular2-services

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

组件:

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/

相关文章:

javascript - 使用 datatrans-inline.js 付款

angular - 单例服务不适用于延迟加载的模块

angular - PDF 不显示图像 : html2pdf library

javascript - 扩展 Angular-CLI 构建过程

angular - 错误 : Cannot match any routes. URL 段: ''

javascript - 如何获取对象数组对象的 Angular 长度

javascript - 返回值与文件内容头相关

javascript - 在 Angular 2 子模块中强制服务实例化(AngularJS 运行 block 的替代方案)

html - 使用服务在组件之间共享数据 - IONIC 2、Angular 2

angular - Angular 2.0 中 $scope 的替代品