Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 10 | Getting query params in URL null or undefined

I have this route with the query param lang:

http://localhost:4200/?lang=de

None of the following examples work, it is always null or undefined

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) { 
  console.log(this.route.snapshot.params.lang);
  console.log(this.route.snapshot.queryParamMap.get('lang'));
}

ngOnInit(): void {
  this.route.queryParams.subscribe(params => {
    let lang = params['lang'];  
    console.log(lang);
  });
  console.log(this.route.snapshot.queryParamMap.get('lang'));
  console.log(this.route.snapshot.params.lang);
}

What am I doing wrong? I have now read several guides, even some for angular 10. Each of them show the above examples, but I still cannot get the value of lang.

like image 869
Roman Avatar asked Jun 18 '26 13:06

Roman


2 Answers

Here is my working solution:

var url = new URL(window.location.href);
var lang = url.searchParams.get("lang");

This works in ngInit and in constructor.

like image 113
Roman Avatar answered Jun 20 '26 02:06

Roman


For the Observable mechanism, you can use paramMap observable like this with an undefined check.

this.route.paramMap.subscribe(params => {
if(params.get('lang')){
    let lang = params.get('lang');  
    console.log(lang);
    }
  });

And other solutions @Leo has already proposed.

Thanks.

like image 40
Riyad Avatar answered Jun 20 '26 02:06

Riyad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!