Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start immediately an Angular 2 Observable when using interval

Tags:

angular

rxjs

I have the following Angular 2 service that is fetching data every 5 seconds:

import { Observable } from "rxjs/Rx";
import { Http, Response } from '@angular/http';


@Injectable()
export class DataService{
  getData():{
    return Observable
        .interval(5000)
        .flatMap(() => this.http.get('http://some_url'))
        .map((res: Response) => res.json())
  }

Is there a way to have this service executing the request at the start? Otherwise it will wait for 5 seconds before the first execution.

like image 790
Ander Avatar asked Jul 22 '26 02:07

Ander


1 Answers

Replace interval with timer, as it allows you to specify an initial delay:

getData():{
  return Observable
    .timer(0, 5000)
    .flatMap(() => this.http.get('http://some_url'))
    .map((res: Response) => res.json())
}
like image 90
cartant Avatar answered Jul 23 '26 18:07

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!