How to call Service after particular interval of time in Angular 4
Sometimes we need to call particular service after interval of time to update data on page so below is solution:
Add below import code in your component.ts file
import { Observable } from “rxjs”;
import { IntervalObservable } from “rxjs/observable/IntervalObservable”;
import { TimerObservable } from “rxjs/observable/TimerObservable”;
import “rxjs/add/operator/takeWhile”;
Declare variable in class
export class MyComponent implements OnInit {private alive: boolean;
}
In ngOnInit() function use below code to call service after particular interval of time
ngOnInit() {IntervalObservable.create(10000) .takeWhile(() => this.alive) // only fires when component is alive .subscribe(() => { this.yourService.getDataList() .subscribe(data => { this.agentData = data.json().result; console.log(this.agentData); }); });}
ngOnDestroy(){ this.alive = false; // switches your TimerObservable off }
Recent Comments