I would like to update my table without refreshing my page but I don't know how to do it as I am a beginner. In my example I use the table from angular material.
how do I update my page every time I add a new element ?
service
public url: string = 'http://localhost:3000/tableInfos';
constructor(private http: HttpClient) { }
getTableDetails(): Observable<PeriodicElement> {
return this.http.get<PeriodicElement>(this.url);
}
create(name: PeriodicElement): Observable<any> {
let newName = {name:name}
return this.http.post<PeriodicElement>(this.url, newName);
}
ts.file
ELEMENT_DATA!: PeriodicElement[]
displayedColumns: string[] = ['name'];
dataSource = new MatTableDataSource<PeriodicElement>(this.ELEMENT_DATA);
constructor(private tableService: TableService) {}
ngOnInit(): void {
this.get();
}
get() {
this.tableService.getTableDetails().subscribe((data:any) => {
this.dataSource.data = data;
});
}
add(name: any) {
this.tableService.create(name).subscribe((data:any) => {
console.log(data);
});
}
json
{
"tableInfos": [
{
"id": 1,
"name": "Hydrogen"
},
{
"id": 2,
"name": "Helium"
}
]
}
interface
export interface PeriodicElement {
name: string;
}
Just use this.dataSource.data = res inside the update function in ts.