Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application.

The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even though the GET call is successfully triggered upon typing, the parameter being sent is always an empty string.

Below is a snippet of my code:

app.component.ts:

export class AppComponent implements AfterViewInit {

    searchBox = null;
    autoComplete = null;

    constructor(private apiService: ApiService) { }

    ngAfterViewInit(): void {
        this.searchBox = document.getElementById('searchBox');

        this.autoComplete = fromEvent(this.searchBox, 'input').pipe(
          map((e: KeyboardEvent) => (<HTMLTextAreaElement>e.target).value),
          filter(text => text.length > 2),
          debounceTime(250),
          distinctUntilChanged(),
          switchMap(s => this.apiService.autoComplete(s))
        );
    }
}

app.component.html:


<div>
  <input type="text" id="searchBox">

  <pre>
    {{autoComplete | async | json}}
  </pre>
</div>

api.service.ts:

export class ApiService {
     autoComplete(s: string): Observable<KeyNames[]> {
        const params = new HttpParams();
        params.append('search', s);

        return this.httpClient.get<KeyNames[]>(this.API_URL + '/tags/autoComplete', {params})
          .pipe(
            catchError(this.handleError('autoComplete', []))
          );
      }
}

Could anyone assist me in understanding why my autoComplete() function always receives an empty string as the parameter?

Answer №1

An issue may arise with the append method as it returns a HttpParams object, indicating that you might need to:

let params = new HttpParams();
params = params.append('search', s);

Alternatively, you can simply do:

const params = new HttpParams().set('search', s);

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

Retrieve elements from a separate pom file

I am looking to organize my web elements by defining them in a separate js file from my test file using Protractor. In my pom.js object, I have set up the following: let web_elements = function() { this.get_login_mail, function() { ...

Why is it necessary to create a model in Angular?

Although I am relatively new to Angular and my understanding of all its concepts is limited, I am curious about the practical use of models in observables. For example, consider this code segment: getRestaurants = (): Observable<Restaurant[]> => ...

What is the rationale behind ngOnInit not being a private method in Angular?

After extensively checking both code samples and even the official documentation, I am still unable to find the information I need. Turning to Google has also yielded no results. The question that baffles me is: ngOnInit() { ... } Why do we use this syn ...

Sharing Data Across Multiple Windows in Angular 2 Using a Singleton List

My multiplayer game involves adding new players to a single game room lobby, which is essentially a list of current players. How can I update this list for all connected players when new ones join? I implemented a service and included it in the providers ...

What is the best way to incorporate master/detail components without relying on hierarchical routes?

I need to combine the following elements. An index page with the route /items (plural). This page should be scrollable. When clicking on individual items, I want to display a detail page with the route /item/:id (singular). The detail page should have a ...

Show JSON information in an angular-data-table

I am trying to showcase the following JSON dataset within an angular-data-table {"_links":{"self":[{"href":"http://uni/api/v1/cycle1"},{"href":"http://uni/api/v1/cycle2"},{"href":"http://uni/api/v1/cycle3"}]}} This is what I have written so far in my cod ...

There is no ElementRef present in the HeaderComponent type

Task: Implement code to detect mouse clicks inside or outside a specified component, leading to an error message stating that 'elementref' does not exist within the 'Headercomponent' type. import { OnInit, Input, Output, ElementRef } f ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

Deploying a nodejs application with angular as the user interface framework using Firebase

Is there a way to set up an express.js application with angular as the front-end framework, multiple route files, and communication between the server and angular via service level API calls, in order to deploy it on firebase using Firebase Hosting? Curre ...

Implementing communication between Resolvers and component methods in Angular 2+

When it comes to loading data from the backend before components are rendered, Angular suggests implementing a Resolver. Instead of creating a Resolver for each component, I am exploring a different approach where the components store the information about ...

Can one inherit under specific conditions?

I have just started exploring the OOP paradigm and I am curious to know if it is possible to have conditional inheritance in TypeScript. This would help avoid repeating code. Here is what I have in mind. Any suggestions or recommendations are greatly appre ...

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...

UI5 Tooling generated an error stating that "sap is not defined" after a self-contained build

Having successfully developed an application using SAPUI5 1.108, I encountered a setback when attempting to deploy it to a system running SAPUI5 version 1.71. The older version lacks certain features, causing the application to fail. In order to address th ...

Incorporate a JavaScript array into a TypeScript document

Having a file named array.js with a large collection of strings, structured like this: module.exports = ["word1","word2",...] I attempted to utilize this array in my validation.ts file by adding the following line: let wiki = require('./array.js&a ...

Problem integrating 'fs' with Angular and Electron

Currently, I am working with Angular 6.0, Electron 2.0, TypeScript 2.9, and Node.js 9.11 to develop a desktop application using the Electron framework. My main challenge lies in accessing the Node.js native API from my TypeScript code. Despite setting "com ...

I'm curious as to why I am receiving an empty array as a response when I send a post request to the API

I am experiencing an issue while sending data to an API using a post method. I have structured the data in an object as per the server's requirements, but upon posting the object to the API, I receive a response with a status of 200 and an empty array ...

Tips on applying borders to dynamically generated content in jspdf autotable, similar to a template

Having trouble adding borders to my PDF generated using jsPDF autotable. I want the layout to match the template, can someone assist me in resolving this issue? I need the header border to consist of two lines, similar to the template image provided below ...

Building an Angular and NodeJS application with Mongoose pagination capabilities

I have a question regarding the design aspect of my project rather than delving into lots of code. My angular client interacts with a MongoDB collection through an HTTP call to a Node.js backend. I am looking to implement pagination for the results. To ach ...

Tips for sending arguments to translations

I am currently implementing vuejs 3 using TS. I have set up my translation files in TypeScript as shown below: index.ts: export default { 'example': 'example', } To use the translations, I simply do: {{ $t('example') }} N ...

Turn off the dynamically generated multiselect dropdown feature (using a plugin) in an angular application

I have included a multi-select dropdown in each row of a table, allowing the user to modify the selection and save it. The configuration for the multi-select dropdown is stored in a TypeScript file. Now, I am looking to disable the dropdown in certain ro ...