I recently made the decision to dive into learning Angular, but I've encountered some difficulties. Specifically, I'm struggling to populate a table with values retrieved from an API using MatTable. Despite receiving the correct values from the API, they just won't show up in the table without any error messages during compilation. I've attempted various solutions to tackle this issue, but none of them seem to work. Any assistance would be greatly appreciated.
HTML:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<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>
<ng-container matColumnDef="animaltype">
<th mat-header-cell *matHeaderCellDef> AnimalType </th>
<td mat-cell *matCellDef="let element"> {{element.animaltype}} </td>
</ng-container>
<ng-container matColumnDef="race">
<th mat-header-cell *matHeaderCellDef> Race </th>
<td mat-cell *matCellDef="let element"> {{element.race}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Typescript:
import { AfterViewInit, Component, ViewChild, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { User } from 'src/app/models/user.model';
import { Adoption } from 'src/app/models/adoption.model';
import { AccountService } from '../services/account.service';
@Component({
selector: 'app-myadoptions',
templateUrl: './myadoptions.component.html',
styleUrls: ['./myadoptions.component.css']
})
export class MyadoptionsComponent implements OnInit {
allAdoption: Adoption[];
dataSource: MatTableDataSource<Adoption>;
displayedColumns: string[] = ['ID', 'name', 'animaltype', 'race'];
user: User;
string: string;
payload;
constructor(private accountService: AccountService) {
}
ngOnInit() {
this.adoptions();
}
public adoptions() {
let resp = this.accountService.getAdoptions(this.getUserId());
resp.subscribe(data => {
this.dataSource = new MatTableDataSource(data);
console.log(this.dataSource.data);
});
}
getUserId() {
this.string = localStorage.getItem('user');
this.user = (JSON.parse(this.string));
if (this.user.token) {
this.payload = this.user.token.split(".")[1];
this.payload = window.atob(this.payload);
const userString = JSON.parse(this.payload);
return parseInt(userString.UserID);
}
}
}
Model:
export class Adoption {
id: number;
name: string;
animaltype: string;
race: string;
UserID: number;
text: string;
adopted: boolean;
}
Console log: Console.log
Table: table