Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Polling with HTTP Client

Polling is a technique used to repeatedly request data from a server at regular intervals. This guide covers the basics of implementing polling using Angular's HTTP Client and RxJS.

Setting Up HTTPClientModule

First, import the HttpClientModule into your app module:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Creating a Service

Next, create a service to manage HTTP requests using the Angular CLI command:

$ ng generate service data

This command generates a new service file named data.service.ts.

Implementing Polling Logic

In the service file, inject the HttpClient and create a method to perform polling using RxJS operators:

// data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable {
    return this.http.get(this.apiUrl);
  }

  pollPosts(intervalMs: number): Observable {
    return timer(0, intervalMs).pipe(
      switchMap(() => this.getPosts())
    );
  }
}

Using the Polling Service in a Component

Inject the service into your component's constructor and use it to perform polling:

// home.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  template: `
    

Posts

  • {{ post.title }}
` }) export class HomeComponent implements OnInit { posts: any[] = []; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.pollPosts(5000).subscribe(data => { this.posts = data; }); } }

Handling Errors

To handle errors in your polling logic, use the catchError operator from RxJS:

// data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, timer, throwError } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable {
    return this.http.get(this.apiUrl).pipe(
      catchError(this.handleError)
    );
  }

  pollPosts(intervalMs: number): Observable {
    return timer(0, intervalMs).pipe(
      switchMap(() => this.getPosts()),
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    console.error('Server Error:', error);
    return throwError('Something went wrong with the request.');
  }
}

Key Points

  • Polling is a technique used to repeatedly request data from a server at regular intervals.
  • Import HttpClientModule in your app module to set up the HTTP Client.
  • Create a service to handle HTTP requests and implement polling logic using the HttpClient and RxJS operators.
  • Use the timer and switchMap operators from RxJS to implement polling.
  • Handle errors using the catchError operator from RxJS.

Conclusion

Polling is a powerful technique for keeping your Angular application data up-to-date. By setting up the HTTPClientModule and using the HTTPClient with RxJS, you can efficiently implement polling and provide a better user experience. Happy coding!