Angular – RxJs throttleTime – Prevent Double Entry API Calls

Table of Contents
Overview
An issue you might run into using events in HTML, are double API calls thus getting double entries in your database. This is where RxJs throttleTime can come in handy.
In this example, an application using <youtube-video> (stateChanged) event calls the API to record if a user has watched the video. The stateChanged event fires twice quickly, therefore not allowing the API to stop the record from being entered twice.
Using throttleTime in an Angular Service
Here is an example of an HTTP request in a service file using the throttleTime function.
Imports
You will need to import the following:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { asyncScheduler, Observable } from 'rxjs';
import { throttleTime } from 'rxjs/operators'
throttleTime Example
In the example service method below the service can only be called every 400 milliseconds.
recordMedia(MediaId: string): Observable<any> {
const URL = `http:localhost:99999/api/productmedia/addimage`;
const throttleConfig = {
leading: false,
trailing: true
}
const body = new HttpParams()
.set('MediaId', MediaId);
return this.http.post(URL,
body.toString(),
{
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
}).pipe(
throttleTime(400, asyncScheduler, throttleConfig)
);;
}
You must be logged in to post a comment.