Access url parameters of pwa address

2019-06-21 03:16发布

问题:

I am new to ionic 2. After a searching everywhere I can not find a direct answer given the following scenario:

  1. I am building a PWA with ionic 2 (because I will later develop hybrid versions of this app)
  2. the address where users will find and access my app will be a standard domain like https://welcometotheapp.com?viewid=0101018737abcdefg
  3. I am using ionic 2, recently installed on windows 10
  4. I have started a new blank app project
  5. My question is NOT related to navigation.

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!

回答1:

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



回答2:

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;
}