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

Alexei picture Alexei · Jun 25, 2018 · Viewed 21.9k times · Source

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+?

Answer

martin picture martin · Jun 25, 2018

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