What is the best approach to display outcomes from a distant query in an Angular-material autocomplete feature?

For my website, I am utilizing angular-material and integrating the auto-complete feature. In the auto-complete function (see codepen here), there is a querySearch function that filters results from a local array of demo search items.

function querySearch (query) {
    var results = query ? self.repos.filter( createFilterFor(query) ) : self.repos, deferred;
    return results;
}

I wanted to modify this function to make a server query after each letter typed. Following guidance on this post, I wrote Angular code to query the server and return a promise.

function querySearch (query) {
    return $http.get('/ajax/user/search/' + query).then(function(data){
        console.log(data); 
        return data.data;
    });
}

However, this modification did not work as expected. The server was successfully queried, but the list of suggestions remained empty. Any assistance on resolving this issue would be greatly appreciated!

Answer №1

Take a look at this example and make sure to turn off the simulate query feature as well as disabling caching of queries - https://material.angularjs.org/latest/#/demo/material.components.autocomplete

Remember to disable cache by setting md-no-cache="false" if you want it to run every time, and also adjust md-min-length="0"

You should modify the timeout used for mocking the query in order to replace it with your real query.

function customQuerySearch(query) {
  var results = query ? self.states.filter(createFilterFor(query)) : self.states,
      deferred;
  if (self.simulateQuery) {
    deferred = $q.defer();
    //change this
    $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);
    return deferred.promise;
  } else {
    return results;
  }
}

Make sure to handle the promise accordingly.

Answer №2

In order to quickly resolve the issue, you can simply modify the function like this:

function findQuery (query) {
    return $http.get('/search/' + query).success(function(data){
        console.log(data); // Data retrieved successfully.
        return data.data;
    });
}

Then, update the function call in the view to:

scan-items="item in ctrl.findQuery(ctrl.searchText)()"

This will now properly execute the returned function.

(Refer to this Codepen for a demonstration of the solution: http://codepen.io/anon/pen/qdyEBz)

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

After attempting to follow a guide, I encountered a scenario where a view was returning None because the is_ajax function was not

After diving into the world of ajax, I encountered a puzzling issue that I can't seem to crack. My hunch is that it involves the comment_id versus the blog_id. (I was following this tutorial: https://www.youtube.com/watch?v=VoWw1Y5qqt8&list=PLKILt ...

Discovering whether an array is empty in Angular8 and retrieving values within a foreach loop

Here is the data that I am working with: I need to inspect the values[] array in each object and determine if it is empty. If the array is empty, I want to return true. However, if the values[] array contains some records, I should return false. I have c ...

Adding pairs of keys and values to an array

I am working with a dictionary-like variable in JavaScript, named "dict". var dict = { val1 : ["a", "b", "c"], val2 : ["d", "e", "f"], val3 : ["g", "h", "i"], ... } My goal is to extract val1, val2, val3 and store them in an array to display as J ...

Is the order of state variables important in React components?

Upon executing the code below, an error "Cannot read properties of null (reading 'login')" occurs, triggered by reaching the return statement at the end. This error persists despite the presence of checks for the boolean before the return stateme ...

Include a series of HTML attributes within an HTML element

I need to take a string of attributes that are formatted in valid HTML and apply them to a specific HTML element, rather than just creating a new string with those attributes. For instance, I have a variable named attributesStr that contains the string of ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Unable to run JavaScript file fetched from cache API

For a web application built using pure vanilla JavaScript without utilizing service workers, I am looking to cache a JavaScript file hosted on an AWS S3 file server explicitly. The script below will be embedded in the index.html file of the application (UR ...

What are some strategies for optimizing React performance when managing controlled input from numerous components?

Building a Parent component with multiple child components, each passing data to the parent for an API call. The structure is as follows: const MainComponent = () => { const [child1input, setChild1Input] = useState(""); const [child2input, setChild ...

Is it possible to achieve the same outcome in JavaScript with these two different code snippets?

I am relatively new to JavaScript and currently exploring the concept of anonymous functions. I created the following code snippet to test my understanding: Code 1: function build(something) { return function(name) { alert("Here is " + someth ...

Is there a way to utilize the child component's method?

I am looking to access a child component's method from the parent in Vue.js. To achieve this, I plan on using $refs. Code Example: <template> <div>Parent!</div> </template> Script: <script> Vue.component('c ...

Enhance information flow within pages using SWR in NextJS

Utilizing SWR in a NextJS project has been a great experience for me. I have successfully fetched a list of data on my index page and added a new entry to the data on my create page. Now, I am looking to take advantage of SWR's mutate feature to updat ...

Issue with implementing Alert component in React Hooks with Bootstrap

Currently, I am working on a project that allows users to nominate their favorite movies. As part of this project, I am trying to implement an alert message that will appear when the submit button is clicked to finalize all the nominations. {"return (" ...

Extract data from JSON using jQuery

Is there a way to extract data from JSON files using AJAX? I am currently fetching JSON data with AJAX and then converting the retrieved data into HTML. The values in the JSON output are not constant, so hardcoding is not an option. Question: How do I pr ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

Contrasting $scope.myFunction() with myFunction($scope)

As I work on developing an Angular app, I have come across two methods for invoking a function that performs a simple multiplication operation. Method 1: function calculate(context) { context.proposition.theoretical_margin = context.propositi ...

Having trouble connecting with Node.js and Express; encountering ERR_CONNECTION_REFUSED

I tried following this basic tutorial: After generating the files as instructed, I ran through all the steps but encountered an issue. Regardless of the browser I used, I kept getting "Unable to connect" in Firefox and "This webpage is not available ... E ...

I am experiencing difficulty with the Click() operation in Selenium web driver as it is not successfully redirecting me to another page

Hello everyone, I could really use your assistance with a problem I'm facing. WebElement wb=driver.findElement(By.name("NavHeader1$tabs$ctl00$btnNavHeaderTab")); Actions act=new Actions(driver); act.moveToElement(wb).perform(); ...

Problem encountered when using multiple tags for the table of contents

My script generates a table of contents based on the headings h2 and h3. The issue arises when there is a span tag within an h2, causing the script to skip that heading and not create a link for it. I suspect the problem lies in the regular expression /< ...

How can I make a Three.js Physijs mesh move towards the mouse?

After browsing through various posts and documentation, I am trying to figure out how to make a BoxMesh follow the mouse cursor. My ultimate goal is to implement joystick touch controls for games like Heroes of Loot. For now, I am focusing on getting direc ...