Navigating in Angular 6 with the router.navigate() method and parsing query

I have encountered a challenge during the development of an application using Angular 6. When passing an object as a value of a property in queryParams: { prop: value}, the built-in function converts the object to a string, resulting in the common JavaScript output of [object Object].

My goal is to utilize my query string for updating the query parameters of the current route. Here's an example of my query string stringified with npm-qs library:

?priceRange[min]=1&priceRange[max] = 2

Now, let's consider the object that I parse using the same library and convert back to an object:

priceRange: {min: "1", max: "2"}

However, queryParams converts it to:

priceRange=%5Bobject%20Object%5D

To resolve this issue, I reparse it into a proper object and then use a method outlined below:

constructor(
  private readonly router: Router,
  private readonly activatedRoute: ActivatedRoute,
) {}

updateQueryParams() {
  this.router.navigate([], {
    relativeTo: this.activatedRoute,
    queryParams: {
      priceRange: {min: "1", max: "2"} (hardcoded this to simplify example)
    }
 });
}

The above code aims to:

  1. Stay on the same page ([] along with relativeTo: this.activatedRoute allows me to remain on the current page);

  2. Adjust the URL to

    .com/?priceRange[min]=1&priceRange[max]=2

Is there a way to successfully use objects as values in queryParams or any other suggestions? I have reviewed the documentation on angular.io, but it does not cover such cases, only providing simple examples like param1=q & param2=w, similar to various posts on Stack Overflow. Perhaps there is a different method within Angular to pass a query string to the URL without using the queryParams of the router.navigate() method.

Thank you in advance!

Answer №1

I used to encounter the bizarre issue of receiving %5Bobject%20Object%5D as my result, until I figured out the solution. This strange output was due to the fact that query parameters should be provided as a second argument.

Here's an example:

this.router.navigate(["/new-path"], { 
  queryParams: { 
    filterOptions: {
      type: "A",
      category: "B"
    }
  } 
});

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

CSS dropdown submenu is not disappearing

I need help with my submenu. I want it to appear when the cursor hovers over a menu item, and for each new menu option selected, the previous submenu should be replaced. Currently, the first submenu stays on the screen and the new one appears underneath it ...

Experimenting with isomorphic-fetch in a ReactJs environment

I have a function that I want to test using mocha and chai's expect method. The function uses "fetch" and "dispatch" as functions. "fetch" is responsible for making AJAX calls to the server. Here is the function: function fetchMetadata() { return ...

Cloud Function experiences a timeout error when attempting to subscribe an FCM token to a topic within the HTTP function

Example Code: Main.ts: import * as admin from "firebase-admin" import fetch, { Headers } from "node-fetch"; interface FooPayload { topic: string, token: string, } exports.foo = functions.https.onCall(async (data, context) => { ...

Issue with CSRF token validation in ASP.NET Core when integrating with Angular

To enhance the security of my application, I decided to implement CSRF-Token protection using Angular documentation as a guide. According to the Angular docs, if a cookie named XSRF-TOKEN is present in the Cookies, it will automatically be included in the ...

Dealing with infinite loop while verifying cookie in angularjs

In my client-side code, my goal is clear. If the user has the cookie, they are authenticated; otherwise, they are redirected to an authentication endpoint on the server. (function() { 'use strict'; angular .module('App', [ ...

What is the method to successfully validate a unique key with Mongoose only if the other key is distinct?

Imagine a scenario where we define this model : const userSchema = new mongoose.Schema({ username: { type: String, unique: true, uniqueCaseInsensitive: true, required: true, }, organisation: { type: Schema.Types.ObjectId, ref: ...

Recharts: Conceal Bars with Missing Values

I am working on a Recharts project that involves a BarChart component displaying 3 different values for each day of the week: primary, secondary, and tertiary. Sometimes, the data for secondary and tertiary is missing. I want the specific Bar components ma ...

Tips for retaining a number even when the page is refreshed

Is there a way to keep the number increasing even after refreshing the webpage? Currently, the number resets every time the page is refreshed. Any suggestions on how to fix this? Here is the number <form method="POST"> &l ...

Error: The object referred to as "procedure" is invalid and cannot be executed as a function

At the moment, I'm delving into creating a small game using NodeJS to explore ES6 features. I've built a "Player" object with the new syntax. The static functions are working perfectly fine. However, when it comes to calling its methods, I encoun ...

Creating a systematic approach for managing errors in Node.js Express

Looking to improve error handling in my Node.js application. Does anyone have advice on creating a centralized error handling system that doesn't rely on try and catch blocks for each API? I'm struggling with this concept and would appreciate any ...

Flask application experiencing issues running AngularJS

I recently came across an interesting tutorial on creating a Pinterest clone, and I thought I'd give it a try. You can check out the tutorial here. However, I've hit a roadblock with getting Angular to function properly in my project. Here&apos ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

Converting Angular 5 select option values to strings is a must

I have set up a basic select connected to a variable like this: <select id="client" name="client" [(ngModel)]="order.clientId"> <option *ngFor="let client of clients" [value]="client.id"> {{ client.name }} </option> </ ...

JavaScript comparing variables to nested object properties

items resembling this are heading my direction: var info = { a0: { name: 'lengthy title 0', var1_min: '10', var1_max: '99', select: ['alpha', 'gamma'], display: 'value0' }, b12: { ...

Choose an option using jQuery with the ability to navigate to the previous or next

I encountered a bug when I tried to click the next or previous button. Below is the HTML code snippet: $("#nextPage").click(function() { $('#pagination option:selected').next().attr('selected', 'selected'); console.log( ...

Node.js Promise delivering less than expected results

I've encountered an issue with a Promise that previously awaited a complete JSON string but now only returns a portion of it. I'm utilizing the Shopify API for customer creation, and this is the expected response structure: { "customer": { ...

Retrieving complex JSON data using PHP

Hey there, I'm fairly new to PHP and trying my best to learn. I have a PHP page that successfully retrieves JSON data and displays it on the page. My issue lies in the fact that my JSON is structured with multiple dimensions, as shown below: {"produc ...

Extract data from a URL using PHP and JavaScript technologies

Upon receiving a json data from a URL, specifically through celery's flower plugin, the following sample is obtained: { "celery@s1": { "scheduled": [], "stats": { "clock": "2535550", "pid": 26002, "broker": { "tran ...

Enable the automatic resizing of a div element

This div features inside: <div class="PF"> <img src="img" class="FollowerPic"> <span>Name</span> <div class="Text"></div> <div class="readURL"> ...

A custom function that changes the state of a nested object using a specified variable as the key argument

My goal is to update the state of an object using a function called updateDatas. This function takes the arguments key, possibly subKey, and value. interface Datas { code: number; item1: Item; } interface Item { id: number; name: string; } const ...