The Mat-autocomplete component is currently displaying outdated data retrieved from the server instead of the most recent information. Is there a way to ensure that only the latest data is shown?

ngOnInit(): void {
    this.filteredAccountOptions = this.accountControl.valueChanges
    .pipe(
      startWith(''),
      map(value => this.accountFilter(value))
    );
    .
    .
    .

The issue arises when the "return this.createDialogService.accountOptions" statement is executed before the subscription part is completed in the "accountSearch(value)" method. This causes the previous data to be displayed.

private accountFilter(value: string): string[] {
    this.accountSearch(value);
    return this.createDialogService.accountOptions
accountSearch(searchedValue: string) {
    this.createDialogService.searchAccount(searchedValue).subscribe(
      (success) => {
        this.createDialogService.accountOptions = JSON.parse(success.message)
      },
      (error) => {}
    )
  }

Here's my HTML code:

<input type="text" matInput [formControl]="accountControl" [matAutocomplete]="auto1">
    <mat-autocomplete #auto1="matAutocomplete">
        <mat-option *ngFor="let option of filteredAccountOptions | async" [value]="option.Name">
             {{option.Name}}
        </mat-option>
    </mat-autocomplete>

Answer №1

To prevent overloading the server, it is recommended to use the switchMap operator when you need to change the data after returning the Observable. Additionally, using the debounceTime function can help manage server requests efficiently.

  ngOnInit(): void {
    this.filteredAccountOptions = this.accountControl.valueChanges.pipe(
      startWith(''),
      debounceTime(3000),
      switchMap(value => this._accountFilter(value)),
    );
  }

  private _accountSearch(searchedValue: string): Observable<any> {
    return this.createDialogService.searchAccount(searchedValue).pipe(
      map(success =>  JSON.parse(success.message)),
    );
  }

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

creating interactive tabs in angular using dynamic json values

Currently I am working on a material tab feature where I aim to dynamically generate tabs based on the values from my JSON data. Below is the JSON data: [ { "regionName": "EMEA", "regionCurrency": "USD", "organizationName": "XYZ", "orga ...

What is the best way to integrate functions using an interface along with types?

Currently, I am working on a school project that requires me to develop a type-safe LINQ in Typescript using advanced types. I am facing a challenge in figuring out how to ensure all my tables (types) can utilize the same interface. My goal is to be able ...

What steps are necessary for TypeScript to retrieve my definitions when utilizing node.js require statements?

I have been utilizing Visual Studio 2013 tools for Node.js along with VS2013 Update 2. In my util.ts file, I have the following code: var Util = function () { this.getSelectOption = function (elem, value) { var x = 99; } module.exports = ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Ensuring input integrity in Lit and Typescript for customized elements

I have been developing custom web controls using TypeScript and Lit, including submit buttons and inputs. However, I am experiencing difficulties when trying to wrap them in a form within my HTML. The inputs are not visible to the form, and the submit bu ...

Which is better: implementing a page system in the backend or the frontend?

I am looking to implement a paging system for database values, which approach is most appropriate? 1-) Should I retrieve all values from the backend and then create a paging system with front end technologies? 2-) Or should I only fetch the values that w ...

Encountering an error with Angular 8-10 and PrimeNG 10 when using the `p

I have been working on a fresh Angular 10 project (also tested with ng 8 and 9): primeng-menu>ng new primeng-menu After setting up the PrimeNG modules: npm install primeng --save as well as npm install primeicons --save In my package.json file: &quo ...

The SWT Browser is failing to display Angular 2 pages within the Eclipse view

I attempted to embed Angular 2 HTML pages within the SWT Browser widget, but it seems that the Angular 2 HTML pages are not displaying correctly inside the SWT Browser. However, I had no trouble embedding Angular 1 (or Angular JS) pages within the SWT bro ...

Typescript provides the flexibility to construct incomplete or partially valid objects

My attempt to create a partial helper function in Typescript led me to an incorrect version that went unnoticed by Typescript: Typescript version: 5.2.2 type A = { a: number; b: string }; // incorrect const buildPartialBad = (key: keyof A, val: A[keyof A ...

SystemJS require in Angular appends extension to .html file

I'm currently working on developing a basic Angular Application with Typescript and utilizing gulp for the building process. My goal is to store the html and css files separately for each component, following this structure: components - app.comp ...

Creating an auth guard in Angular Fire v7 using the latest API (not backwards compatible)

I encountered an issue Error: Unable to handle unknown Observable type when attempting to utilize v7 Angular Fire with the latest API. Specifically "@angular/fire": "^7.4.1" which corresponds to angular 14, firebase 9. Please not ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

When working in React, I often encounter the frustrating TypeError: Cannot read property 'content' of undefined error

Trying to customize a React project, I attempted to add a class to a div using the following code: <div className={styles.content}> In the case of deleting the Data Source, you will lose all configuration sett ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

Sharing component controllers in Angular2 allows for better organization and reuse of

My dilemma involves two separate page components, Services and Users, that share almost identical methods except for the type classes they use. The templates for both components are similar, but they display different class properties. It feels redundant t ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

The requested property is not available on the specified type

Here is a code snippet: import { QueryClient, useQuery, useQueryClient, UseQueryOptions } from "@tanstack/react-query" export function useQueryFactory(getConfig: (queryClient: QueryClient) => UseQueryOptions) { const queryClient = useQuer ...

Creating an array that contains a combination of tuples

I am currently working on converting a function to TypeScript that involves an Array of mixed type tuples, similar to Promise.all. I am struggling to set up the definitions for this particular function. export type Type<T> = [T, boolean]; function f ...

The Angular 4 iframe fails to show the content from the src link webpage

Template: <iframe width="100%" height="100%" [src]="url"></iframe> Component : I have successfully converted the URL into a safeUrl: ngOnInit() { this.url = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.google.com/ ...

What is the most effective way to implement lazy loading using the @defer method in Angular?

I recently discovered a new feature in Angular 17 that allows for easier lazy loading using the @defer directive. I'm interested in learning how to implement it to streamline my existing code base. Currently, I am relying on the router for lazy loadin ...