0

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 .

enter image description here }

How can i call this method every 3 seconds ?

5
  • 1
    which errors setInterval give? Commented May 30, 2022 at 7:42
  • You can do this with setinterval. if you get errors using this, please specify. Commented May 30, 2022 at 7:43
  • Specifying in the edit Commented May 30, 2022 at 7:48
  • Check the edits now please.. @AhmedSHA256 Commented May 30, 2022 at 8:17
  • Maybe try only timer(3000) Commented May 30, 2022 at 8:22

2 Answers 2

2

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 } ); } 
Sign up to request clarification or add additional context in comments.

7 Comments

I tried this as well , it works after every 3 seconds but the problem is i am passing the name variable on click of tab change , and it is remembering the previous values and giving results for all the values of names every 3 seconds . Please see the edit in the question i have mentioned .
you should unsubscribe from the Observable when you change the tab. I updated the example above, it should work.
mySub (Subscription) cannot be assigned null . What should be the initial value for a subscription ? Without initialization also its not allowing .
why it cannot be assigned to null? alternatively you can initialite an empty array and push/pop a subscription in the array.
Compiler is not allowing to assign null during initialization
|
0

Try this, Its works for me

 ngAfterViewInit() { setInterval(() => { this.getDataForClients("simpleName"); }, 3000); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.