Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters.

Is there a way to add one or more search terms to the API URL in order to display only the filtered results?

Below is the code snippet I've written so far which is throwing an error:

src/app/services/customers.service.ts:23:53 - error TS2339: Property 'name' does not exist on type '[]'. 23 queryParams = queryParams.append("name", filter.name);

customers.service.ts

  getAllCustomersList(currentPage: number, filter: []) {

    let queryParams = new HttpParams();
    queryParams = queryParams.append("page", currentPage);
    queryParams = queryParams.append("name", filter.name);

    return this.httpClient.get<Customers>(`${environment.apiUrl}customers`,{params:queryParams});
  }

customers.component.ts

      loadData(filter:[]) {
    
        this.isLoading = true;
    
          this.customerSubscription = this.customersServcice.getAllCustomersList(this.currentPage,filter).subscribe(
              data => {
                this.dataSource.data = data["_embedded"]["customers"];
                setTimeout(() => {
                  this.paginator.pageIndex = this.currentPage;
                  this.paginator.length = data.total_items;
                });
                this.isLoading = false;
              });
      }

      filterChanged(event: any) {
        console.log('Searched value = ' + event.target.value);
        const searchTerm = event.target.value;
    
        this.currentPage = 1;
        this.loadData([])

     }

customers.ts

export interface CustomerItem {
  customer_id: number;
  company_id: number;
  name:  string;
  name2: string;
  address: string;
  post_code: number;
  city: string;
  country_code: string;
  country_name: string;
  phone: string;
  email: string;
  account: string;
  mailing: string;
  sso: string;
  is_customer: string;
  is_vendor: string;
  vat_liable: string;
  vat_number: string
  date_update: string;
  tags: string;
  _links: {
    self: {
      href: string;
    }
  }
}
export interface Customers {
  _links: {
    first: {
      href: string;
    };
    last: {
      href: string;
    };
    next: {
      href: string;
    }
    self: {
      href: string;
    };
  };
  _embedded: {
    customers: CustomerItem[]
  };
  page: number;
  page_count: number;
  page_size: number;
  total_items: number;
}

Here's the HTML code from customers.component.html

    <mat-toolbar class="crm-filters-toolbar mat-elevation-z8">
      <mat-toolbar-row>
        <span>Filter</span>
      </mat-toolbar-row>
      <mat-toolbar-row>
        <mat-form-field appearance="outline">
          <mat-label>Name, email...</mat-label>
          <input matInput (keyup)="filterChanged($event)" placeholder="Name, email...">
        </mat-form-field>

        <!-- Other filter fields go here -->

      </mat-toolbar-row>
    </mat-toolbar>
    <div class="table-container">
      <table mat-table [dataSource]="dataSource"> 
table rows and columns...
      </table>
    </div>

Answer №1

You are specifying the type of filter as an empty array in the getAllCustomerList function.

getAllCustomersList(currentPage: number, filter: any) { // or specify a type if you have one defined.

It's recommended to use a specific type for filters, but if no type is available, using "any" is acceptable.

If the filter is expected to be an Object, you can define it as "any". If it's an array, make sure to indicate that:

 getAllCustomersList(currentPage: number, filter: any[]) { // or Array<any>

Answer №2

To pass them, simply include as an object

let queryData = {
  page: currentPage,
  name: filter[0]
};
// ...
this.httpClient.get<Customers>(`${environment.apiUrl}customers`, {params: queryData });

You're also sending filter: [] as an array. This will only allow for indexing such as filter[0], not filter.name.


Update:
Change the signature to use string[] instead of [] like so

getAllCustomersList(currentPage: number, filter: string[])

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 causes the difference in behavior between packed and non-packed generics?

When attempting to exclude properties outside of generics, it functions properly but results in a breakdown within the generic context. The issue lies in the fact that Omit<Thing, 'key1' | 'key2'> transforms into Omit<Thing, &a ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Learn how to access tag attributes within the ngIf function in Angular 2

considering this structure <a *ngIf="canAccess()" routerLink="/adminUsers">...</a> <a *ngIf="canAccess()" routerLink="/link2">...</a> <a *ngIf="canAccess()" routerLink="/otherlink">...</a> <a *ngIf="canAccess()" rout ...

WebStorm provides alerts for objects, types, and directives within Angular, yet they function properly

Why is WebStorm displaying warnings for objects, types, and directives in Angular Template HTML even though they are functioning correctly? Despite the fact that all types and Angular directives in the HTML structure are working fine within Angular on Web ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

Using Jquery to locate the next div element

I've created this code snippet, but it's not functioning as expected. However, by reviewing it, you can understand my intended outcome: $('.jfmfs-alpha-separator').filter(function() { return ($(this).next().not(".hide-filtered"). ...

Customize the focus function for an individual element

I am working on a custom component that needs to seamlessly integrate with the native blur and focus functions. My goal is to override these functions in order to achieve the specific functionality I need. Currently, I have managed to override the prototy ...

How can we map a promise that resolves to foo to a new promise that resolves to bar?

I am working on a function that uses an XMLHttpRequest to retrieve data and returns a promise with the response. But now I want to modify it so that the promise only contains a specific string from the response. Instead of resolving to response = {status ...

Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo .ts import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './a ...

utilizing jQuery to iterate through JSON data with a random loop

Is there a way to modify this code to display only one image randomly selected from a JSON file that contains multiple images? Here is the code in question: $(document).ready(function() { $.getJSON('https://res.cloudinary.com/dkx20eme ...

Remove the unnecessary space at the bottom of the Mat Dialog

I'm currently utilizing Angular Material within my Angular application. One issue I am facing is the excessive whitespace at the bottom of a dialog that displays information about a post. How can I reduce or eliminate this unnecessary space? Take a l ...

Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript: // Function to add a new account row if (tit.innerHTML === "Add Account"){ var table = document.getElementById(tableId); var row = table ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Button for liking and disliking with Angular, Node.js, and

On my Twitter-esque website, I am developing YouTube-style (like-dislike) buttons. However, when it comes to implementing these like-dislike buttons using Angular, Node.js, and MYSQL with NgFor loop and ngIf conditions, I encountered a problem. My database ...

Mirage blocking Ember.js ajax POST request from going through

Currently, I am in the process of writing tests for a component within my Ember application. This particular component is responsible for executing an ajax POST request to communicate with my servers API and retrieve a file location string as a response. ...

There was an error when trying to read the file '.angular-cli.json'. Please double-check to ensure that the file contains valid JSON format. The error message indicates an unexpected

After installing npm install ng-file-upload, I added the ng-file-upload package to my project. Unfortunately, I am encountering errors in my project now. D:\web\ng4fbbootstrap\node_modules\@angular\cli\models\config&bsol ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...