Home > Blockchain >  Cannot read queryParams in Angular
Cannot read queryParams in Angular

Time:02-05

I am trying to fetch queryParams from url with window.location but query params are not being grabbed.

Example my url is www.abc.com?accountId=123# I am looking for a way to grab accountId=123 as a queryParam or atleast the entire url.

When I used window.location I am getting www.abc.com/#/ instead of www.abc.com?accountId=123#

Why am I not able to read the query params?

Why am I not able to read the query params?

CodePudding user response:

according to the angular documentation you can fetch the query parameters with the activatedRoute in Angular.

In the below example we grab a query parameter "name".

constructor(
  private route: ActivatedRoute,
) {}

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

CodePudding user response:

windows.location return the whole object with URL-related information

if you try to access the location.search then you will get data like ?accountId=123# and you need to get your required data from it

Better to use functionality provided by angular routing as per @Nathan's answer just a minor correction as per your code user accountId in place of the name

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

** Note: here router is an Observable you have to subscribe to it for getting the updated data from it

  • Related