Anguar 2在angular2-datatable中搜索文件管理器 - 属性'first_name'在类型'{}'上不存在
在我的Angular-cli项目中,我使用搜索过滤器为数据表实现了此代码。我使用loadsh在以下链接中使用了教程。 http://plnkr.co/edit/grhag1P85teN4ftggkms?p=previewAnguar 2在angular2-datatable中搜索文件管理器 - 属性'first_name'在类型'{}'上不存在
这里是封装环节:https://github.com/mariuszfoltak/angular2-datatable
我要添加搜索筛选器,它显示我了updateData函数这个错误。 属性'first_name'在类型“{}”上不存在。打字稿或加载版本还是其他问题?
export class UsersComponent implements OnInit {
public users: any = [];
public filteredData: any;
public filterQuery = "";
public rowsOnPage = 10;
public sortBy = "first_name";
public sortOrder = "asc";
ngOnInit() {
this.authService.getUsersList(userData).subscribe(data => {
var res = data.response;
this.users = this.users;
this.filteredData = res.data;
});
}
public updateData(query:string) {
if(query) {
this.filteredData = _.filter(this.users, (a)=>a.first_name.indexOf(query)>=0);
} else {
this.filteredData = this.users;
}
}
}
这里是loadsh版本我的package.json文件
"dependencies": {
"angular2-datatable": "^0.6.0",
"lodash": "^4.17.4",
},
"devDependencies": {
"@types/lodash": "^4.14.50",
"typescript": "~2.0.3"
}
我想在你的IDE发生这个错误(所以它的打字稿错误),所以它是所有关于你的users
阵列的类型为any
和typescript无法检测到类型的first_name属性,我猜测lodash返回为{}
,由于缺少指定类型的数组users
。始终创建类来表示数据是最佳做法。例如:
export class User {
public first_name: string;
/* And the rest of data which coming from your db */
}
/* in your component */
public users: Array<User> = [];
定义类将帮助您保持代码清洁和组织。如果您只是不想创建类,只需使用as
语法并将其与()
一起包装,如下所示。
this.filteredData = _.filter(this.users, (a)=>(a as any).first_name.indexOf(query)>=0);
P.S如果你想使用任何类型和它的阵列使用any[]
或Array<any>
感谢您的建议。我想我每天都要学习新东西:) – parth
只是猜测。尝试使用'a ['first_name']'。 –