使用间隔时如何立即启动Angular 2 Observable [英] How to start immediately an Angular 2 Observable when using interval

查看:43
本文介绍了使用间隔时如何立即启动Angular 2 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Angular 2 服务,该服务每5秒获取一次数据:

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

是否有一种方法可以使此服务在开始时执行请求?否则,它将在第一次执行之前等待5秒钟.

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.

推荐答案

interval替换为

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

这篇关于使用间隔时如何立即启动Angular 2 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆