Home > Back-end >  How to read parameters from the Angular query string
How to read parameters from the Angular query string

Time:12-09

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'

CodePudding user response:

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'));

CodePudding user response:

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

Using this you can get the params

CodePudding user response:

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;
}

CodePudding user response:

router.queryParams returns a Params object, and you can access individual parameters by the parameter name:

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