我正在执行在角度8.0.0中使用REST API提取数据的任务,而这样做的时候我遇到如下错误:
我的任务是在页面的Mat Table中显示数据。
item.ts
import { Execution } from './execution';
export class Items {
items: Exec[];
}
execution.ts
export class Exec {
test: number;
test1: string;
}
execution.component.ts
export class ExecutionComponent implements OnInit {
runData: Items;
constructor(private executionService: ExecutionService) { }
displayedColumns: string[] = ['test', 'test1'];
//@ViewChild(MatSort, { static: true }) sort: MatSort;
dataSource = new MatTableDataSource<Execution>(this.runData.items); //error showing at this point
ngOnInit() {
this.executionService.getArtifactDetails().subscribe(
(response:Items) => {
this.runData = response;
console.log(this.runData);
}
);
}
}
示例JSON
{
"items": [
{
"test": 1,
"test1": "ABC"
},
{
"test": 2,
"test1": "EFG",
]
}
答案 0 :(得分:2)
this.runData
是异步分配的值。因此,必须在订阅中分配了值之后使用它。尝试以下
dataSource: MatTableDataSource<Execution>;
ngOnInit() {
this.executionService.getArtifactDetails().subscribe(
(response: Items) => {
this.runData = response;
console.log(this.runData);
this.dataSource = new MatTableDataSource<Execution>(this.runData.items);
}
);
}
更多信息否如何访问异步数据:https://stackoverflow.com/a/14220323/6513921