Reduce the resource consumption of Angular JS real-time ajax requests

I am using Angular to perform a real-time database search. I have bound the variable $scope.city in my HTML like this:

<div class="col-lg-8">
    <div class="input-group">
     <span class="input-group-addon" id="basic-addon1">City@</span>
     <input type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
    </div>
</div>

Here is the controller code:

app.controller('forecastController', ['$scope','varService','$http', function($scope,varService,$http){


$scope.city = varService.city;
$scope.days = 2;
$scope.$watchGroup(['days', 'city'], function() {   

        $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+$scope.city+'&mode=json&appid=e652a2c384655ea24f5b12d2fb84c60f&cnt='+$scope.days+'&units=metric')
    .then(function(data) { $scope.forecast = data; });

  });

}]);

Currently, the $http.get() method retrieves data every time the $scope.city changes, which is consuming too many resources. I am looking for a solution where it only calls $http.get every 3-4 seconds after the user inputs something. Using $timeout did not solve the issue. Can anyone help me with this? Thank you.

Answer №1

If you find yourself in this scenario, it's crucial to implement some custom logic to handle the situation effectively. For instance, when triggering an event like $watchGroup, it may be necessary to pause execution for a short period before proceeding with your intended process.

Here is a practical guide to assist you through the process:

<div data-ng-app="myApp">
     <div class="col-lg-6" data-ng-controller="myCtrl">
         <div class="input-group">
             <span class="input-group-addon" id="basic-addon1">Country</span>
             <input type="text" ng-model="country" class="form-control" aria-describedby="basic-addon1">
         </div>
     </div>
 </div>
<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('myCtrl', function ($scope, $http, $timeout) {
        $scope.country = "";
        $scope.count = 3;
        var timeoutCheck;
        
        $scope.$watchGroup(['count', 'country'], function () {
            if (timeoutCheck) $timeout.cancel(timeoutCheck);
            timeoutCheck = $timeout(function () {
                alert($scope.country);
                // Make API call here
            }, 3000); // Set desired delay time
        });   
    });
</script>

Answer №2

To add a delay to the model changes, you can utilize ng-model-options. By setting up a delay, you can then use ng-change to execute a function and retrieve your forecast.

<input ng-model-options="{updateOn: 'default blur', debounce: { 'default': 4000, 'blur': 0 }}" ng-change="getForecast(city)" type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">

In your controller, you would have:

$scope.getForecast = function(city) { $http.blahblahblah; }

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

How can I merge disabled dates in react-day-picker-input?

Currently I am exploring the NPM package known as react-day-picker, however, I have encountered a significant lack of documentation regarding the react-day-picker-input element. The documentation briefly mentions a prop named dayPickerProps which requires ...

What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings const questions = [ { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]}, { "id": 1505, "offerings": [ ...

When a label or checkbox is clicked, the absolute positioning triggers a sudden jump to the top of the containing div

Encountering an issue where the user is taken to the top of a scrollable div (absolute position) when clicking a label/checkbox. Code Tried different approaches on an onclick event for each of the 4 labels below, but unfortunately none of them are effect ...

Require help transforming a jquery single function into object instances containing multiple functions

Greetings! I have a database containing a list of teams, each associated with a division. Every team is assigned a "div_id" and a "team_id". I have a jQuery function (dropdown) that takes the div_id and makes an ajax call to retrieve the teams for that div ...

Using Angular for Creating Multiple Checkbox Options

Looking to incorporate multiple <input /> fields that will fill <div> elements with the entered text. Once those are set up, the goal is to add a group of <input class="checkbox"> that, when selected, will wrap the input text with additio ...

Is there a way to adjust the dimensions of the circles?

I came across a code that I wanted to customize by changing the size of the circles. Would it be best to do this using JavaScript or CSS? Is there a way to achieve this modification? The complete code can be found at: https://codepen.io/XTn-25/pen/NWqeBaz ...

Iterate through nested objects in Javascript

I am having trouble extracting only the word from each new instance of the newEntry object. It shows up in the console every time I add a new word, but not when I assign it to .innerHTML. Can someone assist me with this issue? Full code: <style ty ...

Can items be conveniently stored in an MVC Controller?

Forgive me if this question seems trivial, but I am curious about the functionality and best practices involved. If the HomeController has a list as a field and one user adds to it, will that user see the updated list or will it remain empty? Furthermore, ...

There is a necessary pause needed between carrying out two statements

I am currently working with extjs 4.2 and I have encountered a situation where I am loading the store object in the following manner: var userDetailStore = Ext.create('Ext.data.Store', { model: 'Person.DetailsModel', autoLoad: ...

Encountering the error message "Uncaught Error: Objects are not valid as a React child" even though I am not passing objects as children in my React component

My current challenge involves mapping an array of objects, which I retrieved from an axios.get request and then passing them as children to React components. The error message that's causing trouble for me reads as follows: An Error occurred: Objects ...

Can three.js provide a function that mimics the movement of a camera?

In the scenario where I have two models in my scene, I am able to move the camera to various locations within the scene by clicking a button. This is achieved using the following code snippet: camera.position.set(0, 100, -350); //sets initial camera orbit ...

Issue with jQuery AutoComplete display rendering inaccurately

I have encountered an issue with two jQuery autocomplete components on my website. Despite being very similar, one functions correctly while the other does not. The functional code snippet is: @Html.TextBoxFor(model => model.Part, new { @id = "txtPart ...

Ways to utilize a reduce function for field filtering within an object

Can someone help me create a filterStringFields function that accepts an object as input and outputs a new object containing only string-type fields? Here are some examples: Input: { name: 'John', age: 25, city: 'New York' } Output: { ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...

Angular 2+ Service for tracking application modifications and sending them to the server

Currently I am facing a challenge in my Angular 4 project regarding the implementation of the following functionality. The Process: Users interact with the application and it undergoes changes These modifications are stored locally using loca ...

Transmit a label through a web address

Apologies for any language barriers as English is not my first language. I am currently developing an application in JSP and encountering an issue with a field labeled "comments" in one of my forms. Upon form submission, the value of this field is sent to ...

Unable to retrieve data from object properties despite their visibility

I am encountering issues accessing object properties, as they keep returning as undefined. I have attempted console.log(JSON.parse(this.$store.state.user.userId)); as well as console.log(JSON.parse(this.$store.state.user[0].userId)); However, when I ...

Executing code on the server-side (back-end) using Javascript: A step-by-step guide

Imagine wanting to execute JavaScript on the server side instead of exposing the code to the client. For example: Starting with the JS native window Object from the browser. Performing all JavaScript processing in the backend by passing the window Object ...

Obtaining the scene's coordinates in Three.js

Struggling with a coding issue, I've scanned various discussions that don't quite address my specific problem. Any assistance would be greatly appreciated. In my HTML document, I am using the three.js library to create a scene titled scaledScene ...

In mongoose.js, the Model.updateOne() function takes precedence over the Document.save() method when executing

I have been experimenting with MongoDB using mongoose.js to grasp its functionality. My goal is to insert a document and update it. However, upon running app.js, the console logs "Successfully updated," yet when I check the mongo shell, the review: "Pret ...