我的user
数据看起来像这样,导致出现问题...
[{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"Isobel_Renner@hotmail.com"},{"firstName":"Easter","lastName":"Ruecker","username":"Giovani.Collier59","email":"Annamae54@gmail.com"},{"firstName":"Harmon","lastName":"Luettgen","username":"Rosanna51","email":"Moshe98@yahoo.com"},{"firstName":"Angeline","lastName":"Kunze","username":"Gabriel_Braun69","email":"Jackson21@hotmail.com"},{"firstName":"Gayle","lastName":"Bahringer","username":"Dorcas_Roob55","email":"Greyson96@gmail.com"},{"firstName":"Adriana","lastName":"Renner","username":"Serenity.Armstrong42","email":"Sim.Robel@gmail.com"},{"firstName":"Arvid","lastName":"Kiehn","username":"Estrella87","email":"Jaylan_Morissette70@yahoo.com"},{"firstName":"Kristofer","lastName":"Nader","username":"Terence.Walker7","email":"Brady99@hotmail.com"},{"firstName":"Rosa","lastName":"Lebsack","username":"Freida_Hegmann46","email":"Alanna_Schmitt89@hotmail.com"},{"firstName":"Rogers","lastName":"Thiel","username":"Mike_Braun","email":"Agnes.Shields3@gmail.com"}]
我正在使用Angular和导入的Material Angular。我遇到的第一个问题是在数据结构中使用*NgFor
,但是由于Angular V6,您现在可以使用keyValue
管道了,这真的很酷!这样问题就解决了。
然后我想将* NgFor插入表格,以便每个人都填充一行。您不对表使用NgFor,而是使用dataSource-
<table mat-table #table [dataSource]="user">
<!-- table rows -->
</table>
但是再次... Provided data source did not match an array, Observable, or DataSource at getTableUnknownDataSourceError
这就是我获得user
-
export class AppComponent {
error: any;
title = 'toms-app';
user: User;
constructor(private apiServicefile: ApiServicefile) { }
ngOnInit(): void {
this.apiServicefile.getUser()
.subscribe(
(data: User) => this.user = { ...data }, // success path
error => this.error = error // error path
);
}
}
typeScript的新手,以及如何获得所需的结果。请帮忙吗?
答案 0 :(得分:1)
此用户在以下位置不是数组:
{ ...data };
只需这样做:
this.user = data;
或者通过某种方式可以对其进行改进,例如html:
<table mat-table #table [dataSource]="user | async">
<!-- table rows -->
</table>
在TS文件中,您的用户是:
Array<User>
,不是用户,但是当我们使用“ async”管道在html用户中编写代码时,您可以像这样定义它:
Observable<Array<User>> or Observable<User[]>
并将this.apiServicefile.getUser()分配给该字段。
export class AppComponent {
error: any;
title = 'toms-app';
user: Observable<Array<User>>;
constructor(private apiServicefile: ApiServicefile) { }
ngOnInit(): void {
this.user = this.apiServicefile.getUser();
}
}