我正在尝试在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链接
答案 0 :(得分:3)
你的plunker不起作用。你的pboblem是最后两行:
this.company = this.getCompanies(this.companies);
console.log("Filtered company", this.company);
您不应该直接在类中调用方法或console.log。你需要把这个东西放在你的构造函数中。像:
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
})
};
this.company = this.getCompanies(this.companies);
console.log("Filtered company", this.company);
console.log("Companies",this.companies);
}
getCompanies(companies){
if (this.companyId) {
var filtered = companies.filter(function (company) {
return company.empId === this.companyId;
});
return filtered[0];
}
}
答案 1 :(得分:3)
始终在构造函数中运行您的代码,公司也没有companyId
,这将起作用:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<ul><li *ngFor="let c of companies">{{c.empId}} - {{c.empDesc}}</li></ul>
`
})
export class AppComponent {
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);
this.company = this.getCompanies(this.companies);
console.log("Filtered company", this.company);
}
getCompanies(companies){
let self = this;
if (this.companyId) {
var filtered = companies.filter(function (company) {
return company.empId === self.companyId;
});
return filtered[0];
}
}
}