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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With