Angular 如何在Ionic2中基于id筛选数组元素?
我正在使用Ionic2开发一个移动应用程序。其目的是在主页中动态插入人员。每当我们单击一个人时,就会显示一个动态添加的项目列表,这些项目仅与该人相关(具有ID)。我无法筛选每个人的项目,如何仅筛选特定人员ID的项目 这是我添加新联系人条目的主页:Angular 如何在Ionic2中基于id筛选数组元素?,angular,typescript,ionic2,Angular,Typescript,Ionic2,我正在使用Ionic2开发一个移动应用程序。其目的是在主页中动态插入人员。每当我们单击一个人时,就会显示一个动态添加的项目列表,这些项目仅与该人相关(具有ID)。我无法筛选每个人的项目,如何仅筛选特定人员ID的项目 这是我添加新联系人条目的主页: public people:{personName:string, personID:string}[] = []; //will load all the people in the array ionViewWillEnter(){
public people:{personName:string, personID:string}[] = [];
//will load all the people in the array
ionViewWillEnter(){
//addPersons is constructed from addPersonsService
this.people = this.addPersons.getPeople();
}
//from the HTML, it will parse the personID from the array
//it will redirect to the list of items for the specific person
viewDebts(personID:string){
this.navCtrl.push(DebtsListPage, personID);
}
这是addPersonsService
public people: {personName:string, personID:string}[] = [];
//this is called upon click from the HTML
addPerson(person:{personName:string, personID:string} ){
this.people.push(person);
}
getPeople(){
return this.people.slice();
}
generateID(id:string){
return id;
}
在这里,我为每个人显示项目
debtValue:{personDebt:string, personId:string}[] = [];
//this is where the list of items will be displayed
ionViewWillEnter(){
var id = this.navParams; //getting the id from the previous page
this.debtValue = this.debts.getPersonsDebt(id); //debts comes from DisplayDebtsService
}
//adding the item
addDebts(debt:{personDebt:string, personId:string}) {
this.debts.addDebt(debt);
}
最后是DisplayDebtsService
public debt:{personDebt:string, personId:string}[] = [];
addDebt(debt:{personDebt:string, personId:string}){
this.debt.push(debt);
}
getPersonsDebt(id:any){
//this is where I am struggling. How do I filter the results based on the id of the person?
return this.debt;
}
感谢您的帮助您是否已尝试使用
.find()
。。或.filter()
但在这里,我认为find()更好,因为它是ID的过滤器,看起来像PK键。。因此,您只考虑一个人从方法返回,而不是更多人(如filter()do)
比如:
getPersonsDebt(id:any){
//this is where I am struggling. How do I filter the results based on the id of the person?
return this.debt.find(p=> p.id === id);
}
希望它能帮助你谢谢你的帮助。我是按照你说的做的,但现在我面临另一个问题:每当我用id调用getPersonDebt时,我都会遇到这样的错误:类型“{personDebt:string;personId:string;}”不能分配给类型“{personDebt:string;personId:string;}[]”。类型{personDebt:string;personId:string;}中缺少属性“length”。(属性)DebtsListPage.debtValue:{personDebt:string;personId:string;}[]mm它看起来像是将数组作为resosse而不是对象。。因此,请尝试使用过滤器。。像getPersonsDebt(id:any){//这就是我正在努力的地方。我如何根据人的id过滤结果?返回这个.debt.filter(p=>p.id==id);}这个错误现在已经消失了,感谢它非常有用。你能给我解释一下为什么会有不同吗?现在的问题是,在我插入一个值后,它根本不会在屏幕上打印它。我的猜测与我从数组中获取数据的方式有关