【发布时间】:2022-10-06 19:18:23
【问题描述】:
我在一个必须填充 PickList 组件的项目中使用 Angular 13(它是一个简单的 PrimeNG 组件,链接是here)。
我们使用这个组件的方式很简单。我们从后端收到一个列列表,用户必须选择一些或每个列才能创建 DataTable(也是 PrimeNG component)。接下来,我将提供一些代码来展示我们如何做到这一点。
列.ts
export interface Column {
field: string;
header: string;
type: string;
format: string;
editable: boolean;
widthColumn?: string;
}
列服务.ts
getColumns() {
return this.http
.get<any>(url)
.toPromise()
.then(res => <Column[]>res.data)
.then(data => {
return data;
});
}
picklist.component.ts
sourceColumns!: Column[];
targetColumns!: Column[];
ngOnInit(): void {
this.columnService
.getColumns()
.then(columns => (this.sourceColumns = columns));
this.targetColumns= [];
}
但是现在,后端变了,他们增加了一个新字段,即required,如下所示:
export interface Column {
field: string;
header: string;
type: string;
format: string;
editable: boolean;
widthColumn?: string;
required: boolean;
}
所以现在,默认情况下,我必须根据是否需要该列来填充这些列表,使用这个标准。
- 如果需要该列,请推到目标列
- 如果不需要该列,请推到源列
到目前为止我已经尝试过:
this.columnService
.getColumns()
.then(columns => (this.allColumns = columns));
let nonReqCol = this.allColumns.filter(column => column.required == false)
let reqCol = this.allColumns.filter(column => column.required == true)
this.sourceColumns= [...nonReqCol]
this.targetColums= [...reqCol]
但它在控制台上给了我这个错误:
ERROR TypeError: Cannot read properties of undefined (reading \'filter\')
我无法弄清楚为什么这给了我这个错误,因为我(据我所知)在两种情况下都在做同样的事情。
标签: angular typescript list