Home > other >  How to read param from the url in angular
How to read param from the url in angular

Time:11-23

How can I get the value of param2 based on name in angular?

http://localhost:4200/home#parma1=value1&param2=value2&param3=value3

Tried Below:

constructor(
private router: Router,
private route: ActivatedRoute) { }


ngOnInit(): void {
this.route.queryParams
  .subscribe(params => {
    console.log(params);    // Out put : {} 
  }
);
console.log(this.router.url); // Output : /home#parma1=value1&param2=value2&param3=value3

}

Is there any standard approach to get the parameters when parameters separated with # instead of ? ?

CodePudding user response:

This should work. You can follow the https://angular.io/guide/router#activated-route-in-action

this.route.queryParams.subscribe(params => { this.name = params['name']; });

CodePudding user response:

since activatedRoute doesn't recognize params if wasn't seperated by ? based on your example. Just use the traditional URLSearchParams

by this, you can get the value of param2

const params = new URLSearchParams("http://localhost:4200/home#parma1=value1&param2=value2&param3=value3");

const param2 = params.get("param2");
console.log(param2)

CodePudding user response:

try to use queryParamMap

ngOnInit(): void {
this.route.queryParamMap
  .subscribe(params => {
    console.log(params);
  }
)

or use

let param1 = this.route.snapshot.queryParamMap.get('param1')
  • Related