Angular's Material Design Autocomplete feature with remote data sourcing and how its performance compares to the most effective methods

In my current project, I am utilizing an Angular material autocomplete feature that fetches data via AJAX. I am facing a dilemma trying to determine the most efficient approach. Below is a snippet of my code:

$scope.loadOrganizations = function () {
            var url = "index.php?option=com_crm&task=inquiry.loadOrganizations";
            send_data = JSON.stringify({"query": $scope.searchText});
            $http({
                method: "POST",
                url: url,
                dataType: "JSON",
                data: send_data,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
                    xhr.setRequestHeader('Accept', 'application/json');
                }
            }).then(function Success(response) {
                $scope.errors = [];
                if (response.data.state) {
                    $scope.organizations = response.data.results;
                } else {
                    $scope.errors.push({
                        index: $scope.errors.length,
                        error_description: "Something Went Wrong With Loading Existing Data. Please Try Again Later"
                    });
                }

            }, function Error(response) {
                console.log(response);
            });
        };

        $scope.querySearch = function (query) {
            $scope.loadOrganizations();
            var results = $scope.organizations;
            return results;
        };

The issue at hand is the delay in data retrieval when a user inputs a query for the autocomplete feature. The search functionality queries the server and returns data based on a like query which leads to sluggish performance, taking around 250ms to load data. This lag in autocomplete loading time is not ideal for user experience. I am seeking advice on how to optimize this process to enhance efficiency and responsiveness without making users wait for data.

Answer №1

One way to reduce delays when sending requests to the server is by implementing data caching for autocomplete functionality. By pre-loading all organizations at controller initialization and then filtering the results in $scope.querySearch, you can improve performance.

Below is an implementation example:

$scope.querySearch = function (query) {
    var results = _arrayFilter($scope.organizations, function(item) {
        return //condition, such as item.name.indexOf(query) > -1;
    });

    return results;
};

function _arrayFilter(array, predicate) {
    var filteredArray = [];

    for(var i = 0; i < array.length; i++) {
        if(predicate(array[i])) {
            filteredArray.push(array[i]);
        }
    }

    return filteredArray;
}

function _initialize() {
    $scope.loadOrganizations();  // This loads all organizations to $scope.organizations
}

_initialize();

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

The functionality of Angularjs ui-modal is being affected by issues related to the $http request

Currently, I am incorporating Angularjs 1.5.x along with AngularUI Bootstrap. My goal is to initiate a bootstrap modal and populate it with remote data by making use of $http request. To achieve this, I am utilizing the resolve method within the modal&ap ...

Activate audio when the link is clicked

Recently, I created a compact web application and it's almost complete. However, there is one cool functionality that I am missing. My goal is to have a sound play when the user clicks a link, but after playing, I want the navigation to continue as us ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

What are the possible reasons for a checkbox not being checked in React JS?

I've been working with react final form and I'm encountering an issue where I can't seem to get the checkbox to be properly checked. I'm not sure what mistake I might be making. Take a look at my code on CodeSandbox const AppWithIconTo ...

Exploring a JSON Object with nested properties, crafting changes, and producing a fresh object: A step-by-step guide

I am attempting to manipulate a JSON object with nested properties by replacing numeric values with computed values and returning a new object. The original object looks like this: var obj = { "a0": { "count": 41, "name": "Park", "new": { ...

Updating style of element in EJS following POST request in Node.js using Express

I am working on a form page that is supposed to display a Success Alert (Boostrap) once the user fills out the form and clicks the Submit button. <form class="well form-horizontal" action="/contact" method="post" id="contact_form"> ... (input fiel ...

What could be causing ng-submit to not successfully transmit data?

I'm currently going through this Yeoman tutorial, but I'm encountering some issues. The new todo is not being added to the $scope.todos as expected, and I'm struggling to identify the reason behind it. You can access the code here: Upon c ...

Leveraging the power of ES6, achieve recursion with requestAnimationFrame in

Lately, I've been working on creating a versatile SceneManager class that not only manages scenes but also handles rendering. class SceneManager { constructor() { this.scene = new THREE.Scene(); this.camera = new THREE.Perspectiv ...

Ways to delete scheduled tasks in BreeJS

I am currently working on an express server that initiates a recurring job upon client request for a specific duration. The challenge I am encountering is figuring out how to stop and remove that particular job once it has been completed. The following is ...

Tips on accessing a specific block of a file in Rails without having to read it from the start again

I am currently dealing with a continuously growing file (log) that I need to read in specific blocks. To achieve this, I have been using Ajax calls to retrieve a designated number of lines. While attempting to read the necessary lines using File.foreach, ...

Ensuring continuity of session in WebRTC audio calls post page refresh

Currently, I am utilizing the Kandy WebRTC library to facilitate audio calls through WebRTC. One issue I have encountered is maintaining the session alive if a user refreshes the page, as this JavaScript library operates internally using WebSocket. For in ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Can I install more than one instance of Framework7 on the same device?

Currently, I am working on a project using cordova 6.2.0 and framework7 1.6.5. However, now I need to initiate a new project that will be based on cordova 7.1.0 and framework7 2.0.7. I am aware that there is version-manager-cordova-software [1] available ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

The repeated problem persists in Ajax where PHP is producing inaccurate results

Every time I run this code, it keeps showing 0 even when the username and password are correct. I even tried running the PHP code without AJAX and it worked perfectly. PHP include('config/connection.php'); if(isset($_POST['login'])){ ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...