Polling in Angular — How to use RxJS in Angular for polling?

Mousumi Hazarika
Apr 23, 2020 · 2 min read
Photo by Safar Safarov on Unsplash

Polling is a process by which the client continuously request data from the server without any user interaction. It is mainly used to track the long running back-end process status.

With RxJS we can achieve Polling in Angular.

What is RxJS?How it is used in Angular?

RxJS(Reactive Extensions for JavaScript) is a library for reactive programming using Observable that makes it easier to compose asynchronous or callback-based code.

RxJS library is used in Angular.

Let’s get started with an example. Suppose, we have a requirement to update the status of a food delivery, based on actions taking place for this delivery.

In this case, we can use Polling to display the continuous progress of the delivery and stop once the delivery process is completed.

Below are the code snippets to poll the data.

Component

In this component file, we are implementing the polling using RxJS. Here the interval is an Observable and is piped to execute the API call every 5 seconds starting from 0 . Finally, subscribing the observable will give us the response.

In the code we have also unsubscribed the Observable because it prevents memory leakage and is recommended as one of the best practices.

Apart from the Component file, we will also use a Service file, Module file and html Template file.

Template

Below are the code snippets of HTML Template file.

app.component.html

Service

Below are the code snippets of Service file.

app.service.ts

Module

Below are the code snippet for Module file.

This is how we can achieve Polling in angular using RxJS library. Hope this will help the developers who want to use Polling feature in Angular.

The entire code snippet is available in the below GitHub link:
https://github.com/mousumi8/angular-rxjs

Weekly Webtips

Explore the world of web technologies through a series of tutorials