Sai Ram
Sai Ram

Reputation: 103

How to read param from the url in angular

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 ? ?

Upvotes: 1

Views: 214

Answers (4)

Jimmy
Jimmy

Reputation: 1429

Those after "#" called fragment, and the way to get it is

this.activatedRoute.fragment
  .subscribe(frgmt => {
    console.log(frgmt);    // Output (type string): parma1=value1&param2=value2&param3=value3' 
  }
);

if you want param but don't want to use question mark, then use matrix. Something like this: /app;param1=1;param2=2;param3=3

Upvotes: 0

Chady BAGHDADI
Chady BAGHDADI

Reputation: 303

try to use queryParamMap

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

or use

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

Upvotes: 0

Stacks Queue
Stacks Queue

Reputation: 1152

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)

Upvotes: 1

bhathiya.m
bhathiya.m

Reputation: 215

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

Upvotes: 0

Related Questions