Angular provides a convenient way to call an API on key press. Let's delve

How can I trigger an API call in Angular when a user clicks on a textbox during a keypress event? I am encountering an error with the debounce method that says

Cannot read property 'valueChanges' of undefined

app.component.ts

ngOnInit() {

    this.searchField.valueChanges

        .pipe(
            debounceTime(500),
            distinctUntilChanged(),
            map((val) => {
                this.http.post<any>('http://localhost:3000/articles/articleslistData', { pubid: '3', pubdate: this.dateChanged }).subscribe({
                    next: data => {
                        console.log(data);
                    },
                    error: error => {
                        this.errorMessage = error.message;
                        console.error('There was an error!', error);
                    }
                })
            })
        )
        .subscribe();
}

app.component.html

<div class="form-field col-lg-12">
<label class="label" for="message">Headline</label>
<input id="message" class="input-text js-input" type="text" required [formControl]="searchField">
</div> 

Answer №1

Additionally, utilizing switchMap (switchMap "replaces" one observable with another) would look something like this:

this.searchField.valueChanges.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    switchMap ((val) => {
          //we cannot return the "val" directly, instead
          //we need to use it in the HTTP POST request
          return this.http.post<any>('http://localhost:3000/articles/articleslistData', { pubid: '3', pubdate: this.dateChanged })
    })
).subscribe(data => {
   console.log(data);
},
error => {
  this.errorMessage = error.message;
  console.error('There was an error!', error);
}
);

Notice that there is only one subscription in this implementation.

Answer №2

To properly set up your form control, it is recommended to initialize it either in the ngOnInit function or in the property declaration.

export class MyComponent {
  // Option 1
  public formControl = new FormControl({});
  ngOnInit() {
      // Option 2
      this.formControl = new FormControl({});
      // Add your code here
  }
}

Alternatively, you can utilize the FormBuild class for initializing form controls.

For additional information, please refer to: https://angular.io/api/forms/FormControl#initializing-form-controls

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

Numerous instances of Duplicate Identifier errors were encountered during testing of the TypeScript application

After spending all morning searching for a solution... I am using TypeScript with node, npm, bower, and gulp. Whenever I run gulp serve or gulp test, I keep getting the same error message hundreds of times: src\app\main\common\dialogs ...

When an action is clicked within a cell of an Angular Material table row, the (click) event for that row is triggered

Is there a way to activate a modal using a button within a mat-table without triggering the row click event? I've come across Angular Material 2 Table Mat Row Click event also called with button click in Mat Cell but implementing $event.stopPropagatio ...

Svelte: highlighting input text when selected

Is there a way to select the text of an input element when it is focused using bind:this={ref} and then ref.select()? It seems to only work when I remove the bind:value from the input element. Why is that the case, and how can I solve this issue? Thank yo ...

What is the best way to utilize the select all feature in Angular Material select components?

Is it possible for anyone to utilize the array data provided in the URL below? [{"columnName":"Column 1 - Type of Medication\n Number of Medications","selected":false},{"columnName":"Column 2 - Placebo&bsol ...

Is it possible to indicate the base type for a generic function?

Is it possible to define the generic type T as an Object rather than a primitive type like number or string? For example, this clone function should only accept Objects as input. It will destructure the input object o, set its prototype back to that of th ...

Error: Unable to bind 'datasets' as it is not recognized as a valid property of 'base-chart' in ng2-charts

Current Versions: Cordova: 6.3.1, Gulp CLI: 1.2.2, Ionic framework: 2.0.0-rc.0, Ionic CLI Version: 2.1.0 In my Ionic2 application, I have integrated the ng2-charts library. When importing, be sure to use import {ChartsModule} from "ng2-charts/components/ ...

Having issues with jsonConvert.deserializeObject not functioning in angular2 json2typescript

Greetings, I am new to Angular 2 and working on fetching user data from Google, Facebook, and LinkedIn. I am attempting to deserialize an object into an instance of a class I created named UserLogin, but unfortunately it does not seem to be working. Here ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

Bring JSON into Angular 7 application

For my Angular project, I've set up a localization service by importing JSON files. Following this recommended method, I updated my typings.d.ts as shown below: declare module "*.json" { const value: any; export default value; } Everything w ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

Angular 13: Problems arise with custom theme in Angular Material version 13

I've set up a custom theme palette for my project that works perfectly with version ^12.2.13 of Angular Material, but not with ^13.2.3. Here's the SCSS code for my custom theming: my-custom-theme.scss @import '~@angular/material/theming&apo ...

Display a list of items using *ngFor in a dropdown menu without using the optgroup

Is there a way to group data from *ngFor in the dropdown selection without using optGroup? You can find the JSON file link below: JSON Data Typescript Code getProducts() { if (this.products.length < 1) { this.productService.getProducts ...

PHP loader encountered an error: Module "." not found

My current challenge involves attempting to utilize a PHP file instead of an HTML file as the templateUrl for an Angular component. ... @Component({ selector: 'app-register-form', templateUrl: require('php-loader?./register-form.compone ...

Pass the parameter name to the controller using the Change function in Angular 2

When creating a string from multiple inputs, I have a requirement to include the name of the input element as the second parameter in a function. <input [(ngModel)]="programSearched" name="programSearched"(ngModelChange)="stringBuilderOnChangeMaker(pro ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. https://i.sstatic.net/0kFJw.png https://i.sstatic.net/S20cS.png I had it working previously, but unsure when it stopped ...

Setting a default value in a select tag with ngModel in Angular 6

I am currently working with Angular 6 and have the following code snippet: <select class="form-control form-control-sm" #ig="ngModel" [(ngModel)]="assetFormDetails.ig"> <option value="" >S ...

Setting up a route configuration to automatically redirect users to a parent and child route upon app launch

After searching through the Udemy tutorial and Angular2 documentation, I still can't figure out why my redirect isn't working. I want my app to directly navigate to the /whatsup/today component upon loading, but despite successfully redirecting t ...

"Losing focus: The challenge of maintaining focus on dynamic input fields in Angular 2

I am currently designing a dynamic form where each Field contains a list of values, with each value represented as a string. export class Field { name: string; values: string[] = []; fieldType: string; constructor(fieldType: string) { this ...

Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information? I came across an example at the following link: In this example, there is a messageComponent with a "m ...