我想在Angular 2類中實現一個過濾器,但由於某種原因我出現了一個錯誤。我無法過濾並返回結果。Angular 2 - 過濾數組對象不工作
類代碼:
employee = [
{ "empId": "59C", "empDesc": "Software","location":"Dallas"},
{ "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
];
companies : any = [];
comapny : any = [];
test:string="varun";
companyId = this.employee[0].empId;
constructor(){
for (let c of this.employee) {
this.companies.push({
empDesc: c.empDesc,
empId: c.empId
})
};
console.log("Companies",this.companies);
}
getCompanies(companies){
if (this.companyId) {
var filtered = companies.filter(function (company) {
return company.companyId === this.companyId;
});
return filtered[0];
}
}
this.company = this.getCompanies(this.companies);
console.log("Filtered company", this.company);
Plunker鏈接
https://plnkr.co/edit/CnBR4JouNhzH3DWm7QCo?p=preview
謝謝,這工作。但是,爲什麼我們使用,讓自己=這個;在函數中?當我用「return company.empId === self.companyId;」替換自己時,該函數不起作用。你能告訴我爲什麼會這樣嗎? – Varun
,因爲如果我們使用'this',它會引用沒有'comanyId'字段的'companies'數組。換句話說,這個類的「this」將會被它的過濾方法中的'company'數組的'this'遮蔽。 –