Retrieving the observable's object within the component, excluding the HTML Template

I am currently working on implementing a MATERIAL autocomplete feature for my angular project, taking inspiration from this Stackblitz demo: https://stackblitz.com/run?file=src%2Fapp%2Fautocomplete-overview-example.ts

In the demo, they have created an array of 5 states. However, I need to retrieve an array of accounts from a service instead.

The implementation in the demo is quite clear - there's an observable that tracks changes in the text input value and filters the array accordingly based on what has been typed so far.

My challenge lies in the fact that I don't have a complete array of accounts like the example. Instead, I have an observable of the complete array.

 private _filterStates(value: string): State[] {
    const filterValue = value.toLowerCase();
    return this.states.filter(state => state.name.toLowerCase().includes(filterValue));
  }

  private _filterAccount(value: string): COA_Account[] {
    const filterValue = value.toLowerCase();
    // The issue here is that Accounts$ is not an array but an observable
    // How do I work with an observable instead?
    return this.Accounts$.filter(acct => acct.name.toLowerCase().includes(filterValue));
                           
  }

My main question is regarding accessing the content of the observable within the class. While I know how to handle it in the HTML, I believe I may be overlooking something fundamental.

My current approach involves defining an array and populating it when the observable completes:

  ngOnInit(): void {

    this.Accounts$ = this.myAcctSvc.getCOAByProjectId(4200).pipe(
         switchMap((data : COA_Header) =>{
         
          // This works, but I'm unsure if it's the best practice
          this.myAccounts  = data.Accounts;

          return of(this.myAccounts);
        }));
  }

MY QUERY IS: Is there a more efficient way to access the Account[] array through the Accounts$ observable?

Answer №1

If you want to improve your approach to staying in the observable stream as much as possible, consider subscribing to Accounts$ in the template. By utilizing RXJS to manipulate the stream, you can make it react to user input effectively.

To achieve this, I recommend using a reactive form for your input and merging the input stream with the accounts stream like this:

form = this.fb.group({ query: [''] });

// Each new query triggers this stream again
accounts$ = combineLatest([
  this.myAcctSvc.getCOAByProjectId(4200),
  this.form.controls.query.valueChanges.pipe(
    // Start with initial value ('') as valueChanges doesn't emit anything initially
    startWith(this.form.controls.query.value)
  ),
]).pipe(
  map(([accounts, query]) =>
    // Filter accounts based on query if there is one, otherwise return all accounts
      ? accounts.filter((acct) =>
          acct.name.toLocaleLowerCase().includes(query)
        )
      : accounts
  )
);

Check out this stackblitz example

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

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

What is the process of downloading dependencies with the command 'npm install'?

Upon navigating to the folder containing my package.json file for an Angular app, I noticed that when I run the command npm install, it takes a considerable amount of time (around 10 minutes) to download just 6 dependencies. After completion, it download ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

The user authentication service indicates that no user is currently logged in

Currently, I am working on implementing a route guard to distinguish between authenticated users and guests. In order to achieve this, I have created an auth-guard service along with an auth service. Although the user data is successfully stored in the loc ...

React Native Component Error: Cannot read property '_this' of undefined

I am currently developing a face recognition application using React Native 0.63. I'm running my project using react-native run-android. However, I encountered an issue with Component Exception where it shows 'undefined is not an object (evaluati ...

"Utilize Typescript to dynamically check data types during runtime and receive alerts for any potential

INTRODUCTION I am currently working with Angular 6. In Angular, typescript is utilized to allow you to specify the data type of your function's arguments: public fun1(aaa: number) { console.log(aaa); } If I attempt to call fun1 with a parameter ...

Text that adjusts its size based on the available space between columns within a row

I am currently developing an application using angular and bootstrap, and I have a requirement to insert a link between two columns in the third row of iteration. Here is what I have attempted so far: Html: <div class="container"> <div clas ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Managing TypeScript objects

Just starting out with TypeScript and feeling a bit lost. The data I receive from my BackEnd looks like this: { "A": [ { "fieldA": 0, "fieldB": "A", "fieldC": ...

When using PrimeNG's InputOtp component, users are unable to modify the values of input fields

When using the p-inputOtp component from PrimeNG for OTP input, I've observed that changes can be made until three out of four boxes are filled. Once all four boxes are filled, modifying the input is no longer possible. Is there a way to enable change ...

The type '{}' cannot be assigned to the type '{ title: string; text: string; }'

Upon executing the TypeScript code below, I encountered the following error: Type '{}' is not assignable to type '{ title: string; text: string; }'. Property 'title' is missing in type '{}'. The "article" declara ...

Steps for modifying the settings of an express function

According to the documentation, the expected input types for the express Request.send function are defined as (property) Response<any>.send: (body?: any) => Response<any> in the VS Code editor. Is it possible to modify this function to acc ...

Can I include a different website within an Angular project?

I've recently completed an Angular project and now want to embed a page within another Angular page. Specifically, I'm looking to include www.yahoo.com in my Angular application. ...

The movement of particles in tsparticles experiences interruptions when built in React, causing defects in their motion or noticeable stutter and lag

The performance is flawless in development mode with npm run start, but once deployed and running the production build (npm run build), there seems to be a disturbance in particle movement or a drastic decrease in speed. Despite experimenting with all ava ...

Different ways to utilize interface for nested functions

Can someone help me set a better topic for my question? I'm not sure how to do it :) Here's the scenario: I have two functions that share the same interface: interface createMailInterface { to: String, subject: String, message: String } ...

What is the reason behind TypeScript's lack of inference for function parameter types when they are passed to a typed function?

Check out the code snippets below: function functionA(x: string, y: number, z: SpecialType): void { } const functionWrapper: (x, y, z) => functionA(x, y, z); The parameters of functionWrapper are currently assigned the type any. Is there a way we can ...

ng namespace not found

I am currently in the process of converting a simple Angular 1.6 project to TypeScript. I have declared all the necessary typings dependencies and they have been compiled and installed successfully. However, I am encountering a compilation error stating "C ...

Tips for configuring environment variables across multiple test files within Jenkins

In my random.test.ts file I am utilizing an environment variable: test.beforeAll(async () => { new testBase.BaseTest(page).login(process.env.EMAIL, process.env.PASSWORD); }) I want to execute my tests using Jenkins, but I am unsure of how to pass m ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

Encountering numerous TypeScript errors due to a JavaScript file in Visual Studio 2017

Kindly review the update below I utilized the following package as a foundation for my VS Project -> https://github.com/AngularClass/angular2-webpack-starter Everything ran smoothly in Visual Studio Code, but when I attempted to convert it into a Visu ...