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));