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+?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With