I try to put material table using web api data
my response look like :
{
"Code": "1",
"Message": "Role List",
"Data": [
{
"id": 1,
"name": "Employee"
},
{
"id": 2,
"name": "Admin"
}
]
}
when i try to run code i have this "Provided data source did not match an array, Observable, or DataSource"
my html file:
<table mat-table [dataSource]="listUsers" >
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> Id. </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
my component.ts file :
export interface User { name: string; id: number; }const ELEMENT_DATA: User[] = [];
export class ListCompanyComponent implements OnInit
{
displayedColumns: string[] = ['id', 'name' ];
dataSource = ELEMENT_DATA;
listUsers :User[]=[];
constructor(private CommonService:CommonService){}
ngOnInit(): void {
this.getalldata();
}
getalldata()
{
this.CommonService.listUsers().subscribe(data=>{
this.listUsers=data;
})
}
}
my servicefile :
listUsers():Observable<User[]>
{
return this.http.get<User[]>(this.LURL 'users')
}
how to overcome this issue..
CodePudding user response:
Your response is consist of Code
, Message
, and Data
, but clearly what you want to pass to the dataSource
is the Data
part only
So you can modify the getalldata()
method and use data.Data
instead of data
to achieve your goal
{
this.CommonService.listUsers().subscribe(data=>{
this.listUsers= data.Data;
})
EDIT:
You need also to change the type for listUsers()
to receive any
or maybe you can make an interface with your actual response that contains Code
, Message
, and Data
and pass it as the type for your method
listUsers():Observable<any>
{
return this.http.get<any>(this.LURL 'users')
}