Reputation: 335
I am new to ionic 2. After a searching everywhere I can not find a direct answer given the following scenario:
https://welcometotheapp.com?viewid=0101018737abcdefg
My question is how do I go about accessing the url parameter viewid
? I need this parameter so that the app send it to my server side REST api and get the right json data. My users receive the url with the parameter as a link by SMS.
I have tried to make use of several suggestions like this question
But I'm spinning my wheels. I've also watched quite a number of youtube vids from Josh Morony and others but again nothing directly related.
Can someone help with this question? As a newbie, it would be very helpful if code snips were annotated with what code goes in what file given the ionic2 blank template structure. Thanks peeps!
Upvotes: 7
Views: 4341
Reputation: 549
I had to use Location
from @angular/common
. So I believe is worth post another answer:
import { Location } from '@angular/common';
...
public urlParams: any;
constructor(..., public location: Location) {
this.initializeURLParams();
console.log(this.urlParams);
}
initializeURLParams() {
const path = this.location.path(true),
hasParams = /\?(.+?\=.+){1}/;
let params;
if (hasParams.test(path)) {
params = {};
path.split('?')[1].split('&').forEach(both => {
let e = both.split('=');
params[e[0]] = e[1];
});
}
this.urlParams = params;
}
Upvotes: 1
Reputation:
You could try plain old javascript. I dont think this is anything specific to ionic. And because it is not primarily navigation based then the NavParams
would not work, i am guessing.
In .js
you can do a split
like so
let myParam = location.search.split('viewid=')[1];
Note that if there is no viewId=
then the variable will be undefined. Here are the docs for location.search
Upvotes: 3