receive serialized Object as query string parameters in angularjs

835 views Asked by At

I'm sending nested object as Query parameters from AngularJs Controller with the following code:

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

and I have to receive this query string in my other controller as object, I've tried several ways, ended up using the following code:

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

I'm not sure about my method and if there is a cleaner way, as I have to parse the result of first parameter (initval).

The main question here how to properly receive query string, which are originally objects in angularJS? and Is this the right way to send objects as query parameters?

1

There are 1 answers

0
georgeawg On BEST ANSWER

If you are using JSON.parse, you are better off using JSON.stringify:

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

Then decode:

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

The $httpParamSerializer and $httpParamSerializerJQLike services do funky things with arrays that subsequently don't parse well in JavaScript.

The $httpParamSerializer and $httpParamSerializerJQLike services are for communicating with languages and frameworks like PHP and Ruby on Rails.