【发布时间】:2021-08-12 18:15:59
【问题描述】:
我是 Angular 新手,我正在尝试制作一个动态表格来显示数据。
是的,我有它(有点工作)静态数据。
我从这个例子中得到启发:https://stackblitz.com/angular/lrpjroljdly?embed=1&file=app/table-selection-example.html
const COLUMN_DATA: IClusterColumnOrient[] = [...Array(10).keys()].map((_, index) =>({
columnName: (Math.random() + 1).toString(36).substring(7),
schemaName: (Math.random() + 1).toString(36).substring(7),
columnType: (Math.random() + 1).toString(36).substring(7),
id: (Math.random() + 1).toString(36).substring(7),
tableName: (Math.random() + 1).toString(36).substring(7),
databaseName: (Math.random() + 1).toString(36).substring(7),
databaseId: (Math.random() + 1).toString(36).substring(7)
}))
@Component({
selector: 'column-search',
templateUrl: './column-search.component.html',
styleUrls: ['./column-search.component.scss'],
})
export class ColumnSearchComponent implements OnInit{
displayedColumns: string[] = ['select', 'columnName', 'columnType', 'tableName', 'schemaName'];
selection = new SelectionModel<IClusterColumnOrient>(true, []);
@ViewChild('searchInput', { static: true }) searchInput: ElementRef;
columnsData: IClusterColumnOrient[]
isSearching: boolean
columns: string[]
dataSource = new MatTableDataSource<IClusterColumnOrient>(COLUMN_DATA);
这很好用,但是当我想使用动态数据时,我会初始化一个空数组,以及用户输入什么来动态查询我的后端。
constructor(private httpClient: HttpClient){
this.isSearching = false
this.columnsData = []
//Hardcoded as of now, we can import and parse from backend in the future
}
ngOnInit(){
console.log(this.columnsData)
fromEvent(this.searchInput.nativeElement, 'keyup').pipe(
//Find type for js event
map((event: any) =>{
return event.target.value
}),
debounceTime(700),
distinctUntilChanged(),
.....
当我尝试将 COLUMN_DATA 替换为 this.columnData 时,我收到如下错误:
Property 'columnsData' is used before its initialization.
如何用动态数据替换它?
【问题讨论】:
-
请为您的代码的第二个版本创建 stackblitz 示例。
-
不是在构造函数中赋值,而是在变量声明时赋值,即
columnsData: IClusterColumnOrient[] = [];。我假设错误来自 TSlint、ESlint 或类似的东西,这确保您不使用未初始化的属性。代码,如果编译,将正常工作,但严格的检查确保你不会犯任何错误。您可能可以在 linting 选项中的某处禁用它。
标签: angular typescript