How do I call a save function every two minutes in Angular2?
Asked
Active
Viewed 5.0k times
1 Answers
83
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

DeborahK
- 57,520
- 12
- 104
- 129

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
5The interval time isn't rather 12000 (1000ms * 60 * 2), @Günter? ;-) – Thierry Templier Mar 21 '16 at 14:19
-
7If 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 – Blake Apr 01 '17 at 12:32
-
I still don't understand anything you try to accomplish. Why would you do that? What do you mean with "realtime"? Get from where? – Günter Zöchbauer Nov 21 '17 at 08:41
-
Can we use it to fetch data every 2 minute without any use interaction, mean, once user came and it will be working for ever without any use interaction? – Ali Adravi Jan 16 '18 at 15:18
-
3It 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'; – Daryl May 04 '18 at 21:32
-
1Angular 6+, should be import {Observable} from 'rxjs'; – FullStackDeveloper Jul 11 '18 at 14:33
-
@JuniorLeveDeveloper thanks for the hint - updated – Günter Zöchbauer Jul 11 '18 at 14:42
-
1from ng ^6.1 and rxjs ^6.2 you would have to use it like `interval(2000 * 60).subscribe(x => /* do something */)` – Alfa Bravo Oct 05 '18 at 09:31
-
You can refer this, https://stackoverflow.com/a/53082795/3763015 – Vishwa G Oct 31 '18 at 12:09
-
Property 'interval' does not exist on type 'typeof Observable'. – Xb74Dkjb Mar 03 '19 at 04:59
-
@69444091thanks for the hint. I updated my answer. – Günter Zöchbauer Mar 04 '19 at 06:18