Search code examples
angularurlangular5

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


Solution

  • If you already have queryParams: Params, either from building the object yourself or getting it from the current route, you can simply use:

    const queryParamsString = new HttpParams({ fromObject: queryParams }).toString();
    

    queryParamsString will be param1=somevalue1&param2=somevalue2&...

    Don't forget to prepend the ? to it if you're appending this to some URL.