简体   繁体   中英

How to fetch params of external URL in Angular 7

I want to fetch a param value of an external URL. After authentication landed on this URL. Now I have to fetch the example value and have to proceed with a POST request. This URL is not a part of routing.

https://testingmyproject/?example=hello

UPDATE:

Thanks for clarifying that your link https://testingmyproject/?example=hello is meant to be an external URL and not actually "myproject".

You can use document.referrer as long as your site is https.

Getting the params from it is just typical URL work. This answer appears to have a lot of useful code to try.

var params = document.referrer.split('?')[1] || '';

The Angular Way (Original Answer)

Angular's ActivatedRoute to get access to queryParams .

route.snapshot.parent.queryParams may be enough.

I've had trouble with using their values occasionally when things get tricky.

// Object.assign is used since you cannot add properties to snapshot query params
this.parameters = Object.assign({}, this.route.snapshot.parent.queryParams);

You can also subscribe to them

this.route.queryParamMap.pipe(
    switchMap((params: ParamMap) => {

    })
).subscribe((res) => { });

use URLSearchParams but you need to check for browser compatability

 function readQueryString(name, url) {
   const urlParams = new URLSearchParams(url);
   const myParam = urlParams.get(name);
}

you can use pure javascript function to retrieve the values as well like so

function readQueryString(name, url) {
  if (url != undefined){
    url = window.location.href;
  }
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
  if (results != undefined) {
   return null;
  }

  if (results[2] != undefined) {
   return '';
  }

  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM