Angular 13 How to Make REST Search Call using RxJS Debounce ?

In this Angular 13 tutorial, you will learn how to make the API search calls to a remote server in an optimized way. By using the RxJS operators and functions we can minimize the number of API calls made to the server and same time improve the usability of the application by implementing the debounceTime, filter and distinctUntilChanged to bring a magical change in your app.

This application will fetch remote server responses using a third-party API by using the HttpClientModule of Angular to make HTTP calls. By using the RxJS library we’ll control server API hits a user makes while communicating with the server limiting the network resources to optimize the client application.

Many of the real-world applications have search features that filter data fetched from a server or connected to some third-party API. In a normal practice a user types in the query to get related results in response. But in a technical sense if we bind a keyup event on an input search, then on every keyup event an API hit will be made for example if the user types in “car” then three API hits for each character will be made.

This type of behaviour on search inputs can affect application performance a lot as an API hit will be made on every key event to the server.

 

How to optimize the search?

Instead of making a server hit on every keyup event, we can allow a user to type a whole meaningful keyword to make a search for. But how do we know when a user is done? Well, we can set a time that can reset again after a user hits a key, again when a user hits the key it will reset. When a user stops typing this time will up, then we can hit a server API call.

Let’s do this programmatically…

Debounce Time

Debounce Time is the delay that we can add between event subscriptions. Like we can add Debounce Time of 1000 milliseconds which resets after every KeyUp event by a user, if the gap of time between KeyUp event exceeds the 1000 ms then we make a subscription or make API call.

 

Let’s implement Debounce in the Angular 13 application

We can achieve Debounce behaviour in Angular applications using React JS operators. Here in the demo application, we will have a search bar to find movies using free IMDB API services. We will add a debounce on the search bar.

 

 

 

See a working demo here

Get source code in GitHub repo here.

 

# Setup Angular CLI

We’ll create the Angular project in the latest version. Make sure you have updated the Angular CLI tool by running below npm command in the terminal

$ npm install -g @angular/cli

 

# Create an Angular Project

Execute below ng command to create an Angular project.

$ ng new angular-debounce-search
$ cd angular-debounce-search

 

# Update App Component

In the template HTML to make a search, we have an Input field control with a template variable #movieSearchInput to bind keyUp event using RxJs fromEvent method.

The list of searched movies will be iterated using the Angular *ngFor directive creating bootstrap cards for each movie. The isSearching boolean flag show "Searching..." message will show up indicating API hit progress.

Replace the following HTML in the app.component.html file

<div style="margin: 50px;">

  <div class="container" style="text-align:center">
    <div class="row">
      <div class="col-12 text-center">
        <h1>Angular Search using Debounce in RXJS 6</h1>

        <input type="text" #movieSearchInput class="form-control" placeholder="Type any movie name" />

      </div>
    </div>
    <div class="row" *ngIf="isSearching">
      <div class="col-12 text-center">

        <h4>Searching ... </h4>

      </div>
    </div>
    <div class="row">

      <ng-container *ngIf="apiResponse['Response'] == 'False'; else elseTemplate">

        <div class="col-12 text-center">
          <div class="alert alert-danger" role="alert">
            {{apiResponse['Error']}}

          </div>
        </div>

      </ng-container>

      <ng-template #elseTemplate>


        <div class="col-3" *ngFor="let movie of apiResponse['Search']">

          <div class="card" style="margin:5px;">
            <img class="card-img-top" src="{{movie['Poster']}}">
            <div class="card-body">
              <h5 class="card-title">{{movie['Title']}}</h5>
              <p class="card-text">Year: {{movie['Year']}}</p>
            </div>
          </div>
        </div>

      </ng-template>

    </div>
  </div>

</div>

 

In the component class file, using angular’s @ViewChilddecorator we’ll get reference using the template variable  #movieSearchInput on the Input control of type ElementRef. The @ViewChild will have {static:true} set as we will bind event in the ngOnInit() component hook.

@ViewChild('movieSearchInput', { static: true }) movieSearchInput: ElementRef;

 

On Input control, we’ll bind keyUp event using the fromEvent method of RxJS. We’ll pipe() this event triggered using the following operators

filter(): Event will be triggered only when the length of the input value is more than 2 or whatever you like.

filter(res => res.length > 2)
debounceTime(): This operator takes time in milliseconds. This is the time between key events before a user stops typing.
debounceTime(1000)
distinctUntilChanged(): This operator checks whether the current input is sitting from the previously entered value. So that API will not hit if the current and previous value is the same.
searchGetCall(): This method is making the actually HTTP call to the server after passing all scenarios we implemented.

Update the app.component.ts file with the following code.

// app.component.ts
import { Component, ViewChild, ElementRef, OnInit } from "@angular/core";
import { of } from "rxjs";
import {
  debounceTime,
  map,
  distinctUntilChanged,
  filter
} from "rxjs/operators";
import { fromEvent } from 'rxjs';
import { HttpClient, HttpParams } from "@angular/common/http";

const APIKEY = "e8067b53";

const PARAMS = new HttpParams({
  fromObject: {
    action: "opensearch",
    format: "json",
    origin: "*"
  }
});

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {

  @ViewChild('movieSearchInput', { static: true }) movieSearchInput!: ElementRef;
  apiResponse: any;
  isSearching: boolean;

  constructor(
    private httpClient: HttpClient
  ) {
    this.isSearching = false;
    this.apiResponse = [];

    console.log(this.movieSearchInput);
  }

  ngOnInit() {

    console.log(this.movieSearchInput);

    fromEvent(this.movieSearchInput.nativeElement, 'keyup').pipe(

      // get value
      map((event: any) => {
        return event.target.value;
      })
      // if character length greater then 2
      , filter(res => res.length > 2)

      // Time in milliseconds between key events
      , debounceTime(1000)

      // If previous query is diffent from current   
      , distinctUntilChanged()

      // subscription for response
    ).subscribe((text: string) => {

      this.isSearching = true;

      this.searchGetCall(text).subscribe((res) => {
        console.log('res', res);
        this.isSearching = false;
        this.apiResponse = res;
      }, (err) => {
        this.isSearching = false;
        console.log('error', err);
      });

    });
  }

  searchGetCall(term: string) {
    if (term === '') {
      return of([]);
    }
    return this.httpClient.get('http://www.omdbapi.com/?s=' + term + '&apikey=' + APIKEY, { params: PARAMS.set('search', term) });
  }

}

Update App Module

Make sure to add HTTPClientModule in the app.module.ts file to use the HTTP API server calls.

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

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

 

How to add Condition in debouncing using filter operator?

filter operator returns boolean true or false. If we return false debounce will not work. So we can easily add conditional debounce like if we want to check any other value is there before making a hit, then we can do like this.

...
...
        filter(res => {
          if(res && this.user.corpid){
            return true;
          }else{
              return false;
          }
        }),
...
...

 

So in the above example app, we learn how we can implement Debounce Time to optimize search functionality in an Angular application using RxJS v7 Operators.

Conclusion: Using RxJs we can customise the search functionality in the Angular application as it is giving the flexibility to change various operators as we discussed above.

 

Leave a Comment

Your email address will not be published. Required fields are marked *