12

I'm trying to find the equivalent of the $interval from AngularJS into Angular 5.

$interval will repeat a function call or a block a specified number of times with a delay in-between. This is what I would like to do, written in AngularJS:

$interval(function() {
      myFunction(param1, param2)
      i++;
    }, delay, count);

Make abstraction of i, I'm using it for a different purpose. How can this be achieved in Angular 5? I already tried using rxjs/Observable but I can't seem to find a way to include both the delay and the run multiple times part.

Thank you.

Bogdan Pușcașu
  • 545
  • 2
  • 7
  • 21

4 Answers4

16

You may make use of the timer static method and take operator.

import {timer} from 'rxjs';
import {take} from 'rxjs/operators';  

timer(yourDelay, 1000).pipe(
   take(yourCount)).subscribe(x=>{
    // do here whatever you want to do here
    })

I assumed you use RxJS 6.

Community
  • 1
  • 1
siva636
  • 16,109
  • 23
  • 97
  • 135
4

You can use interval with take to control how many times you want to call your function.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';

const delay = 1000; // every 1 sec
const count = 5; // process it 5 times

Observable.interval(delay).take(count).subscribe(() => {
  myFunction(param1, param2);
});
Bk Santiago
  • 1,523
  • 3
  • 13
  • 24
  • This gives me back 'Property interval does not exists on type Observable' at build time. I think this is caused by the version of RxJS. I am using RxJS 6. – Bogdan Pușcașu Apr 30 '18 at 09:12
  • @BogdanPușcașu it should still work even for v6, I've updated the answer, please try adding `import 'rxjs/add/observable/interval';` – Bk Santiago Apr 30 '18 at 09:19
3

You can use interval from rxjs

import { interval } from 'rxjs/observable/interval';

//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => console.log(val));

This will emit new value after every 1 second

ashfaq.p
  • 5,379
  • 21
  • 35
1

You can refer this tutorial for your query. its working fine in Angular 5 also.. I tried it and its given here simple way.

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);   });
 });
}
Prashant M Bhavsar
  • 1,136
  • 9
  • 13