How to start immediately an Angular 2 Observable when using interval

房东的猫 提交于 2019-12-07 12:44:56

问题


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.


回答1:


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())
}


来源:https://stackoverflow.com/questions/42451673/how-to-start-immediately-an-angular-2-observable-when-using-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!