List of suggestions for autocomplete in Angular

My autocomplete function is set up like this:

chooseArtist: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map((term: any) => term.length < 2 ? []
        : this.artistlookuplist.filter((v: any) => v.name.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    )

I also have a service that loads the artistlookuplist like this:

getArtists(): void {
    this.artistService.getSearchArtist(this.searchstring).subscribe((data: any[]) => {
      this.artistlookuplist = data;
    });

I want to integrate these two processes so that the autocomplete suggestions are only fetched when the chooseArtist function is triggered from the autocomplete field.

Any solutions on how to achieve this?

Answer №1

It seems you're looking to merge two observables together. In this case, when combining two observables where one depends on the other, you can utilize the switchMap operator from RxJS.

   import {of} from 'rxjs
   import {debounceTime,distictUntilChahne,switchMap} from 'rxjs/operators' 

   text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term:any)=>{
          return term.length<2? of([]):
          this.artistService.getSearchArtist(term)
      })
    )

In this setup, the initial observable is text$, and depending on the value of "term," a new observable is returned (using the of operator to create an observable containing an empty array if term.length<2, or using the artist service observable).

Think of switchMap as a variation of map - while map transforms the response directly, switchMap allows for transforming the response into a new observable.

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 send an array of objects to a PHP server using axios?

let dataArray = [ { fname: 'name #1', choice: 'choice #1', }, { fname: 'name #2', choice: 'choice #2', }, // more data could be appended here ]; I'm looking for guidance on how to send ...

How to include THREE.js in a Node module along with custom variables and functions

I have been working on adapting a THREE.js project that originally included JavaScript files directly in HTML into a node module-based setup. My goal is to utilize webpack to bundle the project into a single file (bundle.js) so that the HTML only needs to ...

Is there a way to iterate through indexed variables in javascript?

After receiving an array of data from a JQuery .ajax function, I noticed that the fields in the array are named and numbered like part1, part2, part3, etc. I attempted to loop through this data using the code below, but unfortunately, it resulted in NaN: ...

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

Angular 2 encountered an issue trying to identify the module for the ManagersService class

Encountering an issue when attempting to build using ng build -prod. The error message is as follows: ERROR in Cannot determine the module for class ManagersService in C:/Test/src/app/shared/common/managers/managers.service.ts! Add ManagersService to the ...

Creating a Countdown in Javascript Using a Variable

I want the date to change from the first date to the second date. At the start, it should display 'Starts:' in bold followed by the remaining time. Once it switches to the second date, it should show 'Ends:' in bold and then the remaini ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

Uncheck the box for disabling the bottom row of HTML tables

I need help with disabling a check box under certain conditions. Specifically, I want to disable the check box if there is only one row in the table or if it's the last row, but for some reason it's not working as expected. Here is the HTML: &l ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

What is the best way to align a badge icon regardless of the avatar's size?

I'm working on creating an avatar component with badges. However, I'm facing an issue with the positioning of the badges relative to the avatar size. The image below provides a clear illustration of the problem. Can you guide me on adjusting the ...

Patience is key as we await the arrival of the loaded data before making a return in AngularFire 0

I am working on a form that should only be submitted if the user provides a valid access key ($scope.access_key) - and each key can only be used once. Within my controller, I have the following method: $scope.verifyAccess = function() { var ref = new ...

Using ngIf to validate an empty string in Angular 5

I need assistance with validating an empty string retrieved from a server Although it is usually straightforward, it's just not working as expected <div class="ui-g-2 info-txt" *ngIf="appointment.Notes !==null || appointment.Notes !== ...

To work with Typescript, the 'unknown' type needs to be equipped with

I encountered an issue in vscode stating "Type 'unknown' must have a 'Symbol.iterator' method that returns an iterator." for the following line of code: bookmarks.push(...this.$auth.user?.bookmarks); let bookmarks = []; if(this.$au ...

Azure Static Web App does not retrieve the connection string value from environment.prod.ts

After deploying my Angular App to Azure as a Static Web App, everything seemed to be running smoothly. However, I encountered an issue with the file "environment.prod.ts" in the environments folder within my app that contains the following code: export co ...

Creating a personalized filter list in Vue Instant Search: A step-by-step guide

Currently, I'm utilizing Laravel Scout with Algolia as the driver. Vue is being used on the front end and I've experimented with the Vue instant search package, which has proven to be very effective. The challenge I am encountering involves cust ...

I am looking to save the data entered in an HTML form directly into a JSON file within the webpage

I am currently storing the value in an array on the server, but I would like to store it only on the client side within the webpage. I want to write the form data from the HTML form into a JSON file that remains on the page itself and is not sent to the ...

Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later: @app.route("/") def home(): data = {'Language': &a ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...