Efficiently loading and locally filtering data in Angular 2 using Observables

In my Angular 2 application, I have successfully implemented an input with autocomplete that calls an API for server-side filtering and value retrieval. However, I am now facing a challenge as I need to add more inputs to my page that do not require server-side filtering. It would be more efficient to retrieve all values when the component loads and then perform filtering within the component itself.

To achieve this, I have an API call that returns three string arrays which I need to access in my Angular service using the standard method:

getFormFilters(): Observable<FormFilterModel> {
    return this._http.get(this.baseUrl+this.getFormFiltersPath)
      .map(res => res.json() as FormFilterModel);
}

The FormFilterModel interface includes three arrays: array1, array2, and array3.

While I have successfully retrieved the observable containing these arrays, I am struggling to filter them locally. My form inputs are connected to form controls similar to the server-side filtering input, but I cannot figure out how to access and filter the actual arrays within the Observable. Here is where I'm currently stuck with the code:

this.filteredArray1$ = this.searchForm.controls.array1Search.valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => //need help with filtering FormFilterModel$ to return a subset of array1 based on input)

Although I can effectively filter an array using RegExp, accessing the array within the Observable seems to elude me at the moment.

Answer №1

Capture the response from your API request and save it in the designated component. Next, utilize the valuesChanges.map method to filter through the arrays.

ngOnInit() {
  this.retrieveFormFilters().subscribe(formFilters => {
    this.formFilters = formFilters;
  });

  this.filteredArray1$ =  this.searchForm.controls.array1Search.valueChanges
    .debounceTime(300)
    .distinctUntilChanged()
    .map(search => this.formFilters.array1.filter(value => matches(value, search)))
}

Answer №2

Begin by subscribing to the response and then proceed to filter the received object accordingly.

 formFilters: FormFilterModel;
 filteredResults: string[] = [];
 this.serviceOb.getFormFilters().subscribe((formFilters) => {
    this.formFilters = formFilters;
 });

 this.formFilters.array1.filter((data) => {
    this.filteredResults.push(data);
 });

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

Floating navigation bar that appears and disappears as you scroll

My webpage has a dynamic navbar that consists of two parts: navbarTop and navbarBottom. The navbarTop should appear when the user has scrolled down more than 110 pixels, while the navbarBottom should show up when the user scrolls up. The issue I am facing ...

In Rails 3, you can utilize JavaScript to submit a form_tag remotely, however ensure that it submits as

I am trying to implement a form_tag in rails 3 that can be submitted using ajax instead of html through javascript. Despite setting the form to submit as javascript, it still submits as html when clicking the submit button. - form_tag({:controller => " ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

Is it possible to utilize context within a custom hook?

Here is a custom hook that attempts to use context inside it, but results in an error stating "Invalid hook call. Hooks can only be called inside of the body of a function component" export const useFetch = async () => { const { city, setFetchError } = ...

Unlocking the power of the Angular 2 injector at a global level

Is there a way to globally access an instance of the root Angular 2 injector (for example, from the browser console)? In Angular 1, it was done using angular.element(document).injector(). This can be handy during testing and exploration, allowing you to ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

Is it possible for changes made to an object in a child component to be reflected in the parent component

When passing an object to the child component using , how can we ensure that changes made to a specific property in the object within the child component are visible in the parent component? In my understanding, changes would not be reflected if we were p ...

Filter out the selection choice that begins with 'aa' in the drop-down menu

Here is a select field with various options: <select id="sel"> <option value="1">aadkdo</option> <option value="2">sdsdf</option> <option value="3">aasdfsddkdo</option> <option value="4"> ...

Drop down list not showing array values

I am attempting to populate a dropdown list with elements from an array using the Document Object Model (DOM) within a for loop. However, I keep encountering an error stating that the dropdown list is null. Here is the JavaScript code I am using: var st ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Generating forms dynamically using JSON data

Currently, I'm using three nested ng-repeat directives to display multiple questions and their corresponding answers. Everything is displaying correctly so far, but now I need to create a form to save the answers. What would be the best approach to ac ...

Create a new `div` component for a child element when the button is clicked in ReactJS

I am attempting to incorporate a child div component (div-col inside of div-row) when the button is clicked. In this case, I am changing the card layout from grid to list view using Bootstrap classes. If the current view is set to grid view: <div class ...

Why does the outcome of running this code vary each time?

I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on w ...

Guide to dynamically add data to two columns

I have a challenge with organizing multiple inputs into rows with two columns each, ensuring that each input is appended to the appropriate side (50% for each column unless there's an odd number of inputs). Currently, the inputs are being added to se ...

What could be the reason behind the absence of this.props.onLayout in my React Native component?

In my React Native app, I have the below class implemented with Typescript: class Component1 extends React.Component<IntroProps, {}> { constructor(props){ super(props) console.log(props.onLayout) } ... } The documentation for the View ...

Manipulating TextGeometry by both removing and adding it can cause the scene to

My current project involves creating a clock using Text Geometry. To update the time displayed on the clock, I have to remove and recreate a new Text Geometry every time. Unfortunately, this process of adding a new Text Geometry causes my browser to freeze ...

Tips for choosing input content when there is a single error class

I'm trying to determine if there is exactly one div with an error class. If so, I want to use the .select() method to select the content of the corresponding input (within that input's parent div). Any ideas on how to achieve this? This is my a ...

Struggling to determine the type of constant after a specific type check? (TS2349: Unable to call a function on a type that does not have a call signature

Encountered a puzzling issue with TypeScript where it appears that I should be able to recognize that a constant is an array, and then utilize array methods on it. However, TypeScript seems unable to confirm that a value is truly an array even after a dire ...