ronenmiller
ronenmiller

Reputation: 1137

Extracting optional parameter value from url on angular2

I am redirecting to my Angular2 site with some (optional) appended parameters like so:

https://my-site.com/?param1=some-value1&param2=some-value2

So i want to extract the values into variables if they exist:

let value1 = extractValueByParam(url, param1Str);

Can it be done with router variables? Or what is the "correct" way of doing this?

So far the best method I have found is to use window.location.href value and parse it myself, but it does not seem like the right thing to do.

Thanks!

Upvotes: 1

Views: 1030

Answers (2)

slaesh
slaesh

Reputation: 16917

You should use queryParams:

constructor (private _ar: ActivatedRoute) {}

ngOnInit() {
   this._ar.params.subscribe(params => console.log(params)); // params used with '/'
   this._ar.queryParams.subscribe(params => console.log(params)); // optional params used with '?'/'&'
}

official docs:

Upvotes: 1

ZanattMan
ZanattMan

Reputation: 736

In your ngModules set the rout as:

{path: '/:param1/:param2', component: YourComponent}

Then in your component, get the value with the following:

 if(params['param1']){
    var param1 = params['param1'];
 }

Upvotes: 0

Related Questions