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

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Guidelines for transmitting form information to a web API using Angular

I am currently working on an Angular 6 project where I have a form and a table that retrieves data from a web API. I want to know if it's possible to send the form data to that web API. Here is the code snippet that I have so far: HTML Form: &l ...

Best practice for setting up components in Angular 2 using HTML

I have developed a component that relies on external parameters to determine its properties: import { Component, Input } from '@angular/core'; import { NavController } from 'ionic-angular'; /* Info card for displaying informatio ...

Create TypeScript declaration files dynamically within the application's memory

Is there a way to programmatically generate declaration files using TypeScript? I know we can use tsc --declaration --emitDeclarationOnly --outFile index.d.ts, but I'm not sure how to do it in code. For example: import ts from 'typescript' c ...

Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Leveraging Expose in combination with class-transformer

I have a simple objective in mind: I need to convert the name of one property on my response DTO. refund-order.response.dto.ts export class RefundOrderResponseDto { @Expose({ name: 'order_reference' }) orderReference: string; } What I w ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Unexpected Data Displayed by Material UI Modal Component

I'm currently facing an issue with my Material UI Modal component in a React/Typescript project. When a card element is clicked on the site, it should display expanded information in a modal view. However, clicking on any card only shows the most rece ...

``There seems to be a problem with the ngb time picker when using the up and

Currently, I am utilizing Bootstrap 4 and NG Bootstrap time picker for a project in Angular 10. Despite correctly adding all the code, I have encountered an issue where the up and down arrows on the time picker are not functioning as expected. Below is a s ...

What exactly does RouteComponentProps entail?

While exploring information on React, I came across the term RouteComponentProps. For example: import { RouteComponentProps } from 'react-router-dom'; const ~~~: React.FC<RouteComponentProps> and class BookingSiteOverview extends React.Com ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Using XML in Angular for POST requests

I am currently working with Angular (not AngularJS) and have a web service that uses SOAP to interact with XML data. Although I've searched extensively, I haven't been able to find a comprehensive example of a POST request using XML. If anyone ...

How to apply conditional styling to text using Angular2

I need to display a list of objects that contain names and numbers. The color of the name should change based on the number associated with it - red for 1, blue for 2, green for 3, and orange for 4. My template currently looks like this: <p *ngFor="l ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

Tips for showcasing individual row information in a popup window with Angular 9

Here is the code snippet for utilizing the open dialog method in the component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from '../_services/auth.se ...

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...