角材料MatTable MatTableDataSource设置datasource.data到接口并获取错误

时间:2019-06-24 12:45:19

标签: angular material

我有一个有角材料的桌子。我从数据类型界面更改为

dataSource : MatTableDataSource<IAddress>;
dataSource.data = this.testData;
interface IAddress {
  name: string;
  address: string:
  city: string;
  state: string;
  country: string;
  county: string;
  zipcode: string;
}

testData: IAddress[] = [{
 name: 'John Doe', address: '601 Main St', city: 'DC', state: 'DC', zipcode: '11111', county: '', country: 'USA'
}];

这有效并且填充了垫子表。

我需要将数据类型更改为以下

interface IProfile {
  jobTitle: string;
  startDate: string;
  endDate: string;
}

interface IEmployee {
  profile: IProfile;
  address: IAddress[];
}

dataSource : MatTableDataSource<IEmployee >;
dataSource.data = this.testData;

this.Data = {} as IEmployee ;
    this.Data.profile= this.testProfileData;
    this.Data address= this.testAddressData;

我跨过实例化,设置了所有属性,然后可以看到数据。但是,当我按照如下方式将对象设置为数据源时

this.datasource.data = this.Data;

我收到以下错误

类型IEmployee缺少类型IEmployee []中的以下属性:length,pop,push,concat

我将代码更改为dataSource:MatTableDataSource;

它仍然给我同样的错误。

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:1)

数据应为数组,并使用以下方式通过testProfileData和testAddressData对其进行初始化。确保testProfileData是一个对象,而testAddressData是一个数组。然后,您必须按照以下方式将元素推入数据数组。

Data: Array<IEmployee>;

this.Data = [] as IEmployee;
this.Data.push(profile: this.testProfileData, address: this.testAddressData);

// Try the following also if it is necessary and the best practice is to use the existing datasource variable without using useless variable declarations.
this.datasource.data = this.Data;