2016-04-18 47 views
0

我从我的json API获取了一个Peoples(人员对象)的列表,并将它保存在通过this.people访问的变量中。Angular 2 - 从对象数组中获取正确的对象

我需要访问他的支点对象age = 15假设只有一个支点对象defind与15

  1. 我可以访问与角2这种特定的对象年龄的人吗?
  2. 如果不是,我将不得不改变我的API来提出新的请求吗?

在此先感谢!

回答

2

您可以实现自定义的管道:

@Pipe({ 
    name: 'filter' 
}) 
export class FilterPipe { 
    transform(val) { 
    return val.filter((elt) => elt.age === 15); 
    } 
} 

,并使用这种方式:

{{people | filter}} 

不要忘了你的管道加入到要组件的pipes属性使用它:

@Component({ 
    (...) 
    pipes: [ FilterPipe ] 
}) 

你可以使这个管道有点通用的参数S:

@Pipe({ 
    name: 'filter' 
}) 
export class FilterPipe { 
    transform(val, params) { 
    var field = params[0]; 
    var fieldValue = params[1]; 
    return val.filter((elt) => elt[field] === fieldValue); 
    } 
} 

,并使用这种方式:

{{people | filter:age:15}} 
+0

什么的 “ELT” 变量? – TheUnreal

+0

'elt'是数组的一个元素。它提供给箭头函数...“filter”方法迭代数组的值。 –