Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a url string with query parameters from an object in Angular 5+?

I am trying to create a URL from an object in an Angular 5 SPA. My code looks like the following:

import { UrlTree, UrlSegmentGroup, DefaultUrlSerializer, UrlSegment } from "@angular/router";  const urlTree = new UrlTree(); urlTree.root = new UrlSegmentGroup([new UrlSegment("EndPoint", {})], {}); urlTree.queryParams = {   "param1": param1Value,   "param2": param2Value }; const urlSerializer = new DefaultUrlSerializer(); const url = urlSerializer.serialize(urlTree); 

It does the job, but it seems to include significant overhead for such a trivial job and I am wondering if there is a more straightforward method to obtain the url from the object.

My expectation is to have something simple as:

const url = someSerializer.serialize("/segment1/segment2", {    "param1": param1Value,   "param2": param2Value }) 

Question: How to create a url string with query parameters from an object in Angular 5+?

like image 544
Alexei - check Codidact Avatar asked Jun 25 '18 13:06

Alexei - check Codidact


People also ask

Can we pass object in query params in Angular?

Query parameters can be passed using the Router service or the queryParams directive. To access query parameters ActivatedRoute service needs to be used. Complex data types like arrays of objects can also be passed using query parameters however these data types need to be stringified before being passed.

How do I add parameters to a URL query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

Does URL include query string?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.


1 Answers

You can use just Router and UrlSerializer:

constructor(private router: Router, private serializer: UrlSerializer) {   const tree = router.createUrlTree([], { queryParams: { foo: 'a', bar: 42 } });   console.log(serializer.serialize(tree)); // "/?foo=a&bar=42" } 

See demo: https://stackblitz.com/edit/angular-basic-template-3hx9at?file=src/app/hello.component.ts

like image 150
martin Avatar answered Sep 20 '22 15:09

martin