How do I call a save function every two minutes in Angular2?
1 Answer
rxjs 6
import { interval } from 'rxjs'; interval(2000 * 60).subscribe(x => { doSomething(); }); rxjs 5
You can either use
import {Observable} from 'rxjs'; // Angular 6 // import {Observable} from 'rxjs/Rx'; // Angular 5 Observable.interval(2000 * 60).subscribe(x => { doSomething(); }); or just setInterval()
Hint:
Angular >= 6.0.0 uses RxJS 6.0.0 Angular Changelog 6.0.0
11 Comments
Thierry Templier
The interval time isn't rather 12000 (1000ms * 60 * 2), @Günter? ;-)
Blake
If you use the .subscribe method, make sure to unsubscribe from it on ngOnDestroy. If you don't then your function will continue to run when the component is destroyed, e.g., navigating away from your component
Daryl
It should be noted that importing from rxjs/Rx will import the entire rxjs library and increase the size of your deployment bundle. Consider importing only what you need. In this case: import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval';
FullStackDeveloper
Angular 6+, should be import {Observable} from 'rxjs';
Alfa Bravo
from ng ^6.1 and rxjs ^6.2 you would have to use it like
interval(2000 * 60).subscribe(x => /* do something */) |