0

There is a query string that comes in the form of a string as an input parameter of the method. This is not an ActivatedRoute.

http://localhost:4200/users?param1=en&param2=nk

How do I read the values of param1 and param2 Tried like this:

constructor(private router: Router){}
let srcStr = 'http://localhost:4200/users?param1=en&param2=nk';
const tree: UrlTree = this.router.parseUrl(srcStr);
console.log('params = ', tree.queryParams);

As a result, I get an empty object, Or maybe it can be implemented in some other way?

Here is the result of the code below: result

const srcStr = 'http://localhost:4200/users?param1=en&param2=nk';
const tree: UrlTree = this.router.parseUrl(srcStr);
const params = tree.queryParams;
console.log('param1=', params['param1']); // Outputs 'en'
console.log('param2=', params['param2']); // Outputs 'nk'

3 Answers 3

2

Angular's parser doesn't work with a protocol (http://) in the url. Just use the native URL API: https://developer.mozilla.org/en-US/docs/Web/API/URL_API

    let srcStr = 'http://localhost:4200/users?param1=en&param2=nk';
    const url = new URL(srcStr);
    console.log(url.searchParams.get('param1'));
    console.log(url.searchParams.get('param2'));

Sign up to request clarification or add additional context in comments.

Comments

1
const tree: UrlTree = router.parseUrl(
      '/users?param1=en&param2=nk'
    );
    const q = tree.queryParams;
    console.log(q);

Using this you can get the params

Comments

1

I did Like this

getParamValueQueryString(paramName : string, url : string ) {
    let value;
    if (url.includes('?')) {
      const httpParams = new HttpParams({ fromString: url.split('?')[1] });
      value= httpParams.get(paramName);
    }
    return value;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.