Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code:

$scope.redirect = function () {
    const params = $httpParamSerializer({
        initval: {
            user: {
                id: 1,
                name: 'Username',
            }
        }
    })   
    $location.path('/url-to-other-controller').search(params);
})

When it comes to retrieving this query string in another controller and treating it as an object, I've experimented with different approaches and settled on the following code:

let qs = $location.search();
const initval = JSON.parse(qs.initval);
let userId = initval.user.id;

I'm unsure if my approach is optimal, especially since I have to parse the initial parameter (initval).

The main issue at hand is how to correctly handle query strings that are originally objects in AngularJS. Additionally, I'm curious if there's a more efficient way to send objects as query parameters.

Answer №1

When utilizing JSON.parse, it is recommended to also use JSON.stringify:

$scope.redirect = function () {
    const params = {
        initval: JSON.stringify({
            user: {
                id: 1,
                name: 'Username',
            })
        }
    }
    $location.path('/url-to-other-controller').search(params);
})

Subsequently, you can decode as follows:

let qs = $location.search();
const initval = JSON.parse(qs.initval);
let userId = initval.user.id;

The behavior of the services $httpParamSerializer and $httpParamSerializerJQLike with arrays may not parse correctly in JavaScript.

These services, $httpParamSerializer and $httpParamSerializerJQLike, are specifically designed for communication with languages and frameworks such as PHP and Ruby on Rails.

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

Looking for a way to verify the presence of a value within another properties' JSON schema?

Is it possible to validate if a value exists in other properties in the JSON file, rather than the schema file? I've tried searching for keywords like "lookup" or "reference", but all results refer to the schema file, not the JSON data. Here is the s ...

Tally up various figures in all tables

I am dealing with a dynamic table generated from a PHP loop. Below is an example of the table structure extracted from the browser source code: <table class="table"> ... (table content) </table> <table class="table"> ... (t ...

How to nullify the valueChanges pipe in Angular RxJS until the observable is resolved

A challenge I am facing is piping the valueChanges from a select element to trigger the appropriate API request and displaying a spinner until the response is received. Additionally, I am trying to utilize publish() and refCount() methods so that I can use ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

Having trouble retrieving Firebase data to display on a React chart

I am currently utilizing ApexChartJs in my React project. However, when attempting to retrieve dynamic data from my Firebase database, it returns undefined. https://i.stack.imgur.com/8lcnz.png Below is a snippet of code from my project: import React, { u ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...

tips on incorporating chosen while still enabling text input

I am currently utilizing chosen to showcase a single selection from a lengthy array of choices. In addition, I am seeking the functionality to enable users to submit a choice that is not listed among the available options. This customization is specifica ...

Achieve a fading effect on an element as you scroll down the page

I successfully implemented a toggle audio button on my website, but now I would like it to fade in along with the scroll-to-top button that I also have (which operates similarly to the buttons on scrolltotop.com). Is there a simple way to achieve this? He ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Guide on automatically opening downloaded files in a new tab in IE 11 or Edge similar to the way file downloads function in Chrome

I am currently using Windows 10 and implementing msSaveOrOpenBlob in JavaScript to download the AJAX call blob on IE11. I want the PDF file to be opened in a new tab without any prompts, similar to how it works in Chrome. However, even when trying with th ...

Checking the response data using an Angular interceptor

As a beginner in AngularJS, I am looking for a way to intercept all $http requests and redirect to the login page if the response data indicates a 401 error. I would greatly appreciate any assistance with this issue. Thank you! ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

How to get the clean URL in AngularJS without any parameters using $location

One issue I'm facing is related to the URL structure of my application. It currently looks like this: "http://host:port/mySystem?x.system" The addition of x.system in the URL was necessary due to a legacy application requirement, but now I need the U ...

How to retrieve the image source using jQuery

<img src="../img/arnold.png" alt="Arnold"> Is there a way to retrieve the absolute path of this image using jQuery? Currently, when I use img.attr("src"), it only returns "../img/arnold.png", but I need it to return something like "http://site.com/ ...

The error ElementNotVisibleError occurs in Selenium::WebDriver when attempting to use the send_key function with a Chrome browser, as the element is not currently visible

A problem has arisen with the Ruby Selenium script I am running in parallel. The issue occurs when attempting to send text input through send_key on a webpage while using the Chrome browser. Selenium::WebDriver::Error::ElementNotVisibleError: element not ...

Guide on how to navigate users to a new page using react-router-dom v6 within a class-based component

I am facing an issue where I need to redirect the user to '/dashboard' after logging in, but I do not want to use history.push() from react-router-dom v5.2.0 as I have react-router-dom v6 installed. Is there another alternative to achieve this re ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

Trigger Bootstrap Modal using ASP Razor code within MVC Model value execution

I have a web application built with ASP .NET Core and MVC. The app features a side menu that allows the user to navigate through different pages based on their workflow. For example, when a user logs in for the first time, they are directed to the Home pag ...

Utilizing NestJS to pass multiple IDs as parameters in an API

I am working with nestjs for the first time and I've been tasked with creating an API at http://localhost:8000/companies/4/5/8…. Does anyone know how to create this API using the GET(':id') method that can handle multiple parameters? ...