I want to get live data from a database onto a mat grid . I want to refresh the grid with live data every 3 seconds without manually refreshing the page .
I am trying to use subscriptions but it is giving me errors saying no initialization provided .
My TS -
getDataForClients(name:string){
this.dashboardService.getClientsData(name).subscribe(res=>{
this.dataSource = new MatTableDataSource(res);
})
setInterval and timer also giving error outputs .
I have used this is my service -
public getClientsData(name:string){
return timer(0, 5000)
.pipe(
switchMap(_ => this.http.get<any[]>('https://localhost:44395/api/StocksOrders/' name)),
catchError(error => of(`Bad request: ${error}`))
);
}
But the output instead of for that passed variable it is giving for all the variables passed till now . It should only return array with 8 values , but it is returning other arrays as well .
How can i call this method every 3 seconds ?
CodePudding user response:
istead of setInterval you should use interval
from RxJS
import { interval } from 'rxjs';
mySub: Subscription = null;
initializeIntervalDataForClients(name:string){
if(this.mySub !== null){
this.mySub.unsubscribe();
}
this.mySub = interval(3000).pipe(
switchMap(i => this.dashboardService.getClientsData(name))
).subscribe(
res => {
// do your stuff here
}
);
}
CodePudding user response:
Try this, Its works for me
ngAfterViewInit() {
setInterval(() => {
this.getDataForClients("simpleName");
}, 3000);
}