0

I have a polling set up to make AJAX calls on an interval using an Observable. Here's my code:

import { Injectable } from '@angular/core';
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Rx";
import 'rxjs/add/operator/map';


@Injectable()
export class HttpAPIService {
  metrics: Object;

  constructor(private http: Http) {
    // https://thinkster.io/tutorials/angular-2-http
    this.getMetrics('https://jsonplaceholder.typicode.com/posts/1/comments').subscribe(data => this.metrics = data);
  }

  getMetrics(url: string) {
    return Observable.interval(5000)
      .switchMap(() => this.http.get(url))
      .map((res: Response) => res.json());
  }

}

The code waits 5 seconds before doing the first AJAX call. How can I change it so that the first AJAX call happens immediately? Also, if I use the following command in another module, will the subscription make my variable data-binded to the API call that is being called every 5 seconds?

this.variableIWantToBind = this.httpAPIService.getMetrics('https://jsonplaceholder.typicode.com/posts/1/comments').subscribe(data => console.log(data));
Julien Roy
  • 309
  • 3
  • 11
  • 1
    duplicate of https://stackoverflow.com/questions/36612945/how-to-get-an-observable-to-return-data-immediately-and-every-5-seconds-thereaft – Julien Roy Jun 22 '17 at 20:04
  • 2
    I think `.startWith(0)` is still supported. – Zircon Jun 22 '17 at 20:04
  • 1
    Possible duplicate of [How to start immediately an Angular 2 Observable when using interval](https://stackoverflow.com/questions/42451673/how-to-start-immediately-an-angular-2-observable-when-using-interval) – cartant Jun 23 '17 at 01:24

1 Answers1

0

Use .startWith(0) as @Zircon pointed out