Dealing with multiple queryParams in Angular2: Best practices

Need help implementing a filtering mechanism in my new Angular2 app. Looking to filter a list of entries in an array based on around 20 properties. I've set up filters in one component and a list component as a child that is routed to.

Initially, passing just one filter using queryParams through the router was okay:

this.router.navigate(['/findlist'], {queryParams: {'g': myParam}});

Then receiving the filter on the other side:

this.subscription = this.route.queryParams.subscribe(
  (queryParam: any) => this.myFilter = queryParam['g']
);

However, struggling to scale this for multiple potential Params. Trying to figure out how to pass an array of active filters through queryParams without getting errors.

Thinking of maintaining an array of all filters and their states on the send side, updating values in the array whenever a filter button is clicked, then passing the entire array through queryParams each time.

On the receive side, would need to process the Param as an array and extract each entry as variables to process in the filter. Want to avoid repetition and cycle through an array instead.

Open to suggestions on improving this workflow or alternative methods to pass filter data. Considering creating a separate filter service and using @Input instead.

Any ideas appreciated! (Self-taught amateur so might be missing something obvious!)

Thanks, Tony

Answer №1

If you want to give it a shot, here's a suggestion:

Start by creating an array containing your query parameters:

myParams = [
    { id: 1, param: 'myParam' },
    { id: 2, param: 'myParam' },
    { id: 3, param: 'myParam' },
    { id: 4, param: 'myParam' },
    { id: 5, param: 'myParam' },
];

Combine this array into a single query parameter:

this.router.navigate(['/findlist'], {
    queryParams: {
        filter: JSON.stringify(this.myParams)
    }
});

To read the query parameter, follow these steps:

this.route.queryParams.subscribe((params: any) => {
    if (params.filter){
        console.log(JSON.parse(params.filter));
    }
});

You should see something like this:

https://i.sstatic.net/WJmii.png

Now you can work with this object. The URL might not look great but it should work fine. Give it a try and hopefully it proves helpful to you!

Answer №2

Give this a try.

this.router.navigate(['/go-to-list'], { queryParams: { id: '123', name: 'John' } }); 

The resulting URL will be

localhost:4200/go-to-list?id=123&name=John 

To retrieve the route parameters, use the code snippet below,

this.route.queryParams.subscribe((params: any) => {
    if (params.id){
        console.log(JSON.parse(params.id));
    }
 if (params.name){
        console.log(JSON.parse(params.name));
    }
});

Answer №3

This code snippet worked perfectly for me:

onSubmit() {
    let parameters = {}
    parameters['age'] = '50'
    parameters['gender'] = 'male'      
    this.router.navigate(["/go"], { queryParams: parameters})
  }

Once the function is triggered, the URL will be localhost:4200/go?age=50&gender=male

Don't forget to subscribe to your query params afterwards.

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

Tips for incorporating state properties into a component

Currently engrossed in a project revolving around state management for individual components utilizing Angular 7 and NGRX. The challenge at hand is to ensure scalability of the implementation, allowing multiple uses while maintaining independence. Thus fa ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

How can I effectively build an Angular Library containing various components?

I am currently restructuring the core elements that form a search page into an angular library. My goal is to include various components in this angular library, such as SearchControls, PageHeader, PageFooter, and more. I intend to insert <search-contro ...

Creating HTML elements dynamically based on the value of a prop within a React component

In my React component built using Typescript, it takes in three props: type, className, and children The main purpose of this component is to return an HTML element based on the value passed through type. Below is the code for the component: import React ...

Error: Expected an expression but found a parsing error in the eslint code

interface Address { street: string, } export const getAddress = (address: Address | null) : string => address?.street ? `${address?.street}` : '0000 Default Dr'; Why am I receiving the error message Parsing error: Expression expected ...

Can you explain the distinction between needing ts-node and ts-node/register?

Currently, I am conducting end-to-end tests for an Angular application using Protractor and TypeScript. As I was setting up the environment, I came across the requirement to include: require("ts-node/register") Given my limited experience with Node.js, I ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

Error message stating 'Module not found' is displaying in the browser console

As a beginner with Angular CLI, I recently executed the following commands at the root of my Angular project. issue-management\src\webui>ng generate module pages\dashboard issue-management\src\webui>ng generate component pag ...

Node Sass was unable to locate a binding for the current environment you are using: OS X 64-bit running Node.js 12.x

Currently, I am encountering an issue while constructing an Angular project. The error message that I am facing is as follows: ERROR in Module build failed (from ./node_modules/sass-loader/lib/loader.js): Error: Missing binding /XXXXXXX/node_modules/nod ...

Expanding IntelliSense and helpful tooltips in VSCode for JavaScript and TypeScript by utilizing Node.js for a deeper understanding

As a beginner in programming, specifically in JS/TS, I've been experimenting with node.js and have encountered a puzzling issue with the IntelliSense or 'helptext' feature in VSCode. For instance, when attempting to use fs.open(), I receive ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

How can we combine two phone calls and display the outcomes using typeahead ngx-bootstrap?

Let me walk you through the code that is currently working: <input [formControl]="search" [typeahead]="suggestions" typeaheadOptionField="name" (typeaheadOnSelect)="onSelectedDriver($event)&qu ...

In Typescript, which kind of event is suitable for MouseEvent<HTMLDivElement>?

My goal is to close the modal when clicking outside the div element. Take a look at my code below. // The onClose function is a setState(false) function. import { useRef, useEffect } from 'hooks' import { MouseEvent } from 'react' imp ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Troubleshooting Angular2 Error: Incompatibility with TypeScript - Unable to Assign String

While working on creating a custom pipe in Angular2 for filtering, I encountered the following build error: Error TS2322: Build: Type '() => string' is not assignable to type 'string' Below is my sample code: import { PipeTransf ...

Develop a Java RESTful server with an Angular 5 client that utilizes POST and PUT syntax for communication

Currently, I am in the process of learning the HTTP REST/CRUD protocol in an attempt to establish communication between a Java RESTful servlet and an Angular5 client. I have successfully implemented the GET and DELETE functionalities, however, I am encount ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...