Creating a Request to Retrieve Data from an API with Multiple Filtered Values in an Angular Application

In my Angular app, I have a set of checkbox filters that trigger API queries to fetch filtered results when clicked by the user. Currently, each filter works independently, but I'm struggling to create a function that can store ALL selected filters at once. The function utilizes a Mongoose/MongoDB feature to pass field-specific key/value pairs in the payload of a post request.

My existing code handles one filter at a time using if/else statements. For example, if the type is "lan", it assigns the corresponding value. If no value is given (all filters are deselected), an API call is made without any parameters:

    onFilterReceived(value, type) {
        if (type === 'lan' && value) {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting",
                "languages.primary" : { $in: value }
                });
        } else if (type === 'zip' && value) {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting",
                "zipCode" : { $in: value }
                });
        } else {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting"
            });
    }

The values and types are passed through Angular's Output() and EventEmitter() like this:

        <list [records]="records"
            (sendLanguage)="onFilterReceived($event, type = 'lan')"
            (sendZipcode)="onFilterReceived($event, type = 'zip')">
        </list>

While this setup functions as intended, my goal is to modify it so that multiple filter values can be sent simultaneously over the API. When the received value corresponds to "lan", I want it applied to "languages.primary", and for "zip", to "zipCode". This way, I can include values from all active filters in the request.

I've experimented with different approaches, including if/else statements, but haven't achieved the desired outcome yet. If anyone could provide a simple example or guidance on how to structure this logic effectively, I would greatly appreciate it.

Answer №1

body: any = {'services.workflow.status':'consulting'};

private processType(name: string, para: any) {
    if (this.body[name]) // checking if filter exists and toggling
        delete this.body[name];
    else
        this.body[name] = { $in: para };
}

onFilterReceived(para: any, type: string) {
    if (type == 'lan') {
        this.processType('languages.primary', para);
    }
    if (type == 'zip') {
        this.processType('zipCode', para);
    }
    if (type == 'nat') {
        this.processType('services.service', para);
    }
    console.log(this.body);

    this.filtersService.getByFilter(this.page, this.pagesize, this.body)
        .subscribe(responseData => {
                       this.records = responseData;
                   },
                   errorResponse => this.errorMsg = errorResponse
        );
}

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

The Angular 6 View does not reflect changes made to a variable inside a subscribe block

Why isn't the view reflecting changes when a variable is updated within a subscribe function? Here's my code snippet: example.component.ts testVariable: string; ngOnInit() { this.testVariable = 'foo'; this.someService.someO ...

The AngularJS directive fails to display any content within its element children

Trying to retrieve the innerHTML of the selected node in options The <i class="before"></i> tag should display text from either the selected or the first option when the page loads, within the same group. However, only dropdowns with hardcoded ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

"Seeking assistance in pinpointing a memory leak issue within an Express application running

The issue at hand My Node application running in ECS seems to be experiencing memory leaks, with the memory continuously growing and dropping after each deployment. To investigate further, I generated a heapdump and imported it into Chrome DevTools for a ...

Using jQuery to replace a character in a text

What is the best approach for replacing characters within a text? Take, for example: <script>alert("Hi i am nishant");</script> In this scenario, I need to replace < and > with their corresponding ASCII codes. How can I achieve this? ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

Encountering a NextJS error when attempting to access a dynamic route

I am currently working on a Next.js application that involves dynamic routing. I have encountered an error message stating: Error: The provided path X0UQbRIAAA_NdlgNdoes not match the page:/discounts/[itemId]`.' I suspect that the issue may be relat ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Replicating a Div Click Event using Enzyme and React

I've recently started working with Enzyme and writing tests for an application developed by a team. One of the test cases involves simulating a click on an element that toggles the display of a check-mark image. The application consists of a list wher ...

Database hosted on Heroku platform

Curious to know, if you utilize Heroku for hosting, what database do you prefer? Do you lean towards PostgreSql, MongoDB, or another option altogether? I initially developed a bot using sqlite3, but quickly discovered that Heroku does not support it and ...

Issues with the functionality of the AngularJS button directive

Currently, I am working on developing a RESTful API utilizing Angular and NodeJS. However, I have encountered an issue where a button to navigate to the details page of my application is unresponsive. While I believe the button itself is correctly coded, I ...

Utilizing Gulp to maintain the sequence of streams and files while consolidating them into a single document

I am looking for a solution in my Gulp task to compile HTML templates to javascript from the /views directory, combine them with other javascript sources from the /js directory, and merge them all into one file. It is crucial that the files are concatenat ...

Modifying a section of the source name using jQuery continues to occur repeatedly when the window is resized

I have written a piece of code that is designed to identify the src attribute of all images within a specific div and modify the src name when the window width is less than 900 pixels. The code works perfectly when the page is refreshed, but I encounter an ...

Implementing dynamic rotation of a cube in A-Frame using Javascript

I have been experimenting with A-Frame and Socket.io recently. I have successfully managed to rotate a cube/box statically using the following HTML code: <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9"> <a-animation id="cube ...

How to securely authenticate with Spring using end user credentials in an Angular application

I currently have a set of RESTful web services that are supported by Spring Boot. These services are secured with basic HTTP authentication. I am working on developing an Angular2 front end, which will be hosted on a separate server. My goal is for the fr ...

What steps can I take to ensure my dynamic route functions correctly in NextJs?

// /home/[storeId]/layout.tsx import prismadb from "@/lib/prismadb"; import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function DashboardLayout({ children, params, ...

Cease the execution within the promise.then block

Embarking on my nodejs journey has been an exciting experience. While I have a background in other programming languages, the concept of promises is new to me. In my nodejs environment, I am using expressjs + sequelize. I'm currently working on setti ...

Is it possible to replicate a slow image loading experience in React.js?

Referenced the solution below How to simulate slow loading of image Slowing down internet connection with Chrome DevTools works, but the entire site loads slowly. I want to specifically focus on slowing down the image reloading. One of the suggestions w ...

Collaborating ASP.NET MVC and WebAPI token sharing

Within my ASP.NET MVC and Angular2 application, I rely on Identity Server 3 for user authentication. The usual process involves users logging into the MVC application, which then saves the token in a cookie. Once logged in successfully, users can perform ...

tips on transferring information with jQuery ajax

I have a function in my ASP.NET Webforms application that returns multiple lat and lon values: directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDir ...