Angular2 restricts Http requests within a specified time interval

I am a beginner with angular 2 and I have a value that is linked to user interaction that needs to be sent over http requests. The value can change multiple times per second, so I want to limit the http requests to one every 2 seconds during user interaction. I do not want to send an http request when there is no interaction. I am looking to accomplish this using a timer or interval in Angular 2:

onChange() {

  if(_interval.timerFinished) {
      http.get(.............);
      _interval.launchTimer(2000); //2 seconds
  }

}

Perhaps I can achieve this by utilizing: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/interval.md

Answer №1

I'm interested in reducing the number of http requests

To achieve this, you can connect the element by including it in the HTML as follows:

[(ngModel)] = "searchQuery" [ngFormControl]="searchQueryControl"

Then, in your code:

// Make sure to import these components:
import {FORM_DIRECTIVES, Control} from 'angular2/common';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

constructor ( ... ) {
    //...
    this.searchQuery = '';
    this.searchQueryControl = new Control();
    //...

    this.searchQueryControl
        .valueChanges
        .debounceTime(1000)
        .distinctUntilChanged()
        .subscribe(text => {

            if(text !== '') {
              this.searchQuery = text;

              // Perform necessary actions with the text
            }
      });

    //...
}

Implementing this approach ensures that the code is executed only when there are changes in the input (

this.searchQueryControl.valueChanges
), and when no other change occurs within a second (.debounceTime(1000)). The distinctUntilChanged() method allows us to execute the code only if the value differs from the previous time it was executed. Therefore, if a user types 'asd', deletes it, and then retypes 'd' again, it will not trigger any action.

Answer №2

Have you considered using the debounce operator? Check out more information about it here

If you're interested, you could also explore Sample or ThrottleFirst.

For additional details, take a look at this link: http://reactivex.io/documentation/operators/sample.html

Here's an example of how you can use debounce with HTTP requests:

http.get(.............).debounce(2000)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for handling numerous observables in Angular 7

I am working on an Angular 7 application that deals with a total of 20 sensor data. My goal is to receive data from a selected sensor every 5 seconds using observables. For example: var sensorId = ""; // dynamically chosen from the web interface var senso ...

Converting an array into an object by using a shared property in each element of the array as the key

I have an item that looks like this: const obj = [ { link: "/home", title: "Home1" }, { link: "/about", title: "About2" }, { link: "/contact", title: "Contact1" } ] as const and I want to p ...

Iterate through controls to confirm the accuracy of the password输入 unique

Struggling a bit here since ControlGroup is no longer available. I need to ensure that two passwords match on the front end. this.updatePassordForm = _form.group({ matchingPassword: _form.group({ password: new FormControl('' ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

TypeScript is unable to detect the .sequelizerc configuration file

I have a file called .sequelizerc which contains the following configuration: const path = require('path'); module.exports = { config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'), 'migrations-path': ...

Navigating through a React application with several workspaces - the ultimate guide

Currently, I am working on implementing a monorepo setup inspired by this reference: https://github.com/GeekyAnts/nativebase-templates/tree/master/solito-universal-app-template-nativebase-typescript In this repository, there are 4 distinct locations wher ...

Unleashing the Power of RXJS: Discovering the Magic of connecting Events and Tapping into Executions with retrywhen

Whenever Angular attempts to establish a connection, I aim to display "Connecting". Although I can achieve this on the initial connection, I am uncertain about how to accomplish it when using retryWhen(). It is essential for me to intercept the actual exec ...

Learn how to utilize React lazy effectively in components that utilize Redux compose without any similarities to type 'IntrinsicAttributes'

Here is the structure of a component that is exported with compose from redux. This component is called TestInspector.tsx export interface TestInspectorProps { closeInspector: () => void; onExpand: () => void; isFullScreen: boolean; selected ...

When selecting a MenuItem, only a ReactOwner has the ability to add a ref using addComponentAsRefTo(...)

I'm currently working on a basic component that looks like this: class App extends React.Component<{}, {}> { constructor() { super(); } render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div> ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

Verify using ngIf whether an Angular component is an array or not

Is it possible to target a specific component of an array rather than just checking for a variable in Angular? <div class="someComponent" *ngIf="someVariable"> For instance, how can I use the array component someArray[] with the ...

Tips for verifying internet connectivity and accessing stored data in localstorage

I'm working on my home.ts file and I need to use localStorage items when the internet connection is offline. However, I am encountering numerous errors when trying to add an IF condition in my code. Specifically, I want to access the getItem method be ...

The Element type does no feature a Typescript property

Despite my attempts to include a declaration file and various other solutions, I'm still struggling with this issue: The goal is to define the visible property as a function on the HTML Element object. However, the linter keeps flagging visible with ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Setting up Angular 7 to interact with a .Net Core Web API in Visual Studio 2017

I have been on a quest to find the solution to my programming dilemma. The issue at hand involves a Visual Studio 2017 (Community) project that contains an Angular 7 app with a .NET Core web API backend all within the same project. I have successfully test ...

Issue encountered while appending query parameters to HTTP request

While utilizing mock data and the InMemoryDbService similar to the tour of heroes example, I encountered an issue when passing HttpParams. The data loads successfully without any parameters, but as soon as I add them, I receive a 500 response with the erro ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

Avoid the occurrence of the parent's event on the child node

Attempting to make changes to an existing table created in react, the table is comprised of rows and cells structured as follows: <Table> <Row onClick={rowClickHandler}> <Cell onCLick={cellClickHandler} /> <Cell /> ...

Having trouble resolving the '@angular/material/typings/' error?

I am currently working on tests for an angular project and encountering errors in these two test files: https://pastebin.com/bttxWtQT https://pastebin.com/7VkirsF3 Whenever I run npm test, I receive the following error message https://pastebin.com/ncTg4 ...