RRB
RRB

Reputation: 2116

Extract URL parameter

I am trying to get a URL parameter from the following URL

http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);    
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}

Upvotes: 1

Views: 80

Answers (3)

StepUp
StepUp

Reputation: 38104

You can use ActivatedRoute to get your route params. In addition, it is possible to get always fresh parameters by using queryParamMap. Because queryParamMap returns Observable<ParamMap>:

constructor( 
        private route: ActivatedRoute
)

this.route.queryParamMap.subscribe(params => {
    let userId = params.get('userId ');
});

Upvotes: 1

Lia
Lia

Reputation: 11982

you can also try in your destination Component:

@Component({
  selector: 'app-a',
  template: `
  <h1>A</h1>
  <p> params: {{params | json}}</p>
  <p> query params: {{queryParams | json}}</p>
  <p> url: {{url}}</p>
  <p> full url: {{fullUrl}}</p>`
})
export class AComponent  {
  params;
  queryParams;
  url;
  fullUrl;

  constructor(private route: ActivatedRoute, private router: Router ) { }

  ngOnInit() {
    this.params = this.route.snapshot.params;
    this.queryParams = this.route.snapshot.queryParams;
    this.url = this.route.snapshot.url.join('');
    this.fullUrl = this.router.url;  
  }
}

working DEMO

Upvotes: 2

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

You can use URLSearchParams and its .get function to get the query string value.

const str = 'http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==';
const urlParams = new URLSearchParams(str);
const userId = urlParams.get('userid') || '';

console.log(userId);

Upvotes: 2

Related Questions