RxJSでポーリングする方法


ポーリング処理をするサービスのソースコード

app.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Subject, Observable, interval } from 'rxjs';
import { flatMap, takeWhile } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  subject = new Subject<any>();

  data$ = this.subject.asObservable();

  constructor(
    private http: HttpClient
  ) {
    this.polling().subscribe(data => {
      this.subject.next(data);
    });
  }

  polling(): Observable<any> {
    return interval(1000).pipe(
      flatMap(() => this.http.get('http://localhost:3000/data')),
      takeWhile(() => true),
    );
  }
}

あとは、data$をsubscribeするだけ。