我尝试了以下方法:
portfolioList: MatTableDataSource<Portfolio>;
ngOnInit(): void {
this.backend.getStatement().subscribe(
list => {
if(list as Portfolio[])
this.portfolioList = new MatTableDataSource(list);
}
);
}
Portfolio
为接口。
我得到一个错误:
Error: src/app/admin/statement/statement.component.ts:28:53 - error TS2345: Argument of type 'Object' is not assignable to parameter of type 'Portfolio[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'Portfolio[]': length, pop, push, concat, and 28 more.
28 this.portfolioList = new MatTableDataSource(list);
为什么我得到错误,我如何修复它?
我试过用typeof()
和instanceof
代替as
。但是我无法修复这个错误。
您需要首先检查list
是一个数组,并且数组中的所有项目都是Portfolio
类型。
if (Array.isArray(list) && list.every(item => item instanceof Portfolio)) {
this.portfolioList = new MatTableDataSource(list);
}