Angular 4 how to get url parameters

angulartypescript

Need help again!

I am using Angular 4 and would like to get the parameters from a url in my component. URL is "http://myhost/index?user=James&token=123&picture=3456abc.png" or "http://myhost/index?user=Peter"

I tried these varies methods, but without luck.

How can I get the url parameters 'user', 'token' and 'picture'?

import { Routes, RouterModule, Router, ActivatedRoute, RouteSegment, Params, ROUTER_DIRECTIVES } from '@angular/router';

  constructor(private restSvc: RestSvc, private router: Router, private domSanitizer: DomSanitizer,
    private mdIconRegistry: MdIconRegistry, private activatedRoute: ActivatedRoute, private routeSegment: RouteSegment) {

    // Method 1: subscribe to queryParamMap - not working - all values are undefined
    /*    this.activatedRoute.queryParamMap.subscribe(params => {
          this.userName = params['user'];
          this.userToken = params['token'];
          this.userPicture = params['picture'];
        }) */

    // Method 2: use the $location service - not working
    //var params = $location.search('user', 'token', 'picture');  //syntax error - cannot find name $location

    // Method 3:  RouteSegment
    this.userName = routeSegment.getParam('user'); // Error:  compile eror - has no exported member 'RouteSegment'.    

    console.log("App Component Constructor - params user [" + this.userName + "]");
  }

— Resolved —————————–

I have tried activatedRoute approach, but didn't work. At the end, I go back to the basic suggested by Rach. It works now. The url that I am trying to parse is not from route.navigate. It is a redirection from my server. Not sure it matter or not.

Lesson learned: sometimes, it is good to go back to the basic, i.e. simply parsing the location.href string by & and = to get the parameters.

Best Answer

First, set the ActivatedRoute in your constructor

constructor(private route: ActivatedRoute){}
public user:your_type;

Secondly, put this code in constructor callback:

this.route.params.subscribe(params => { this.user = params['user']; });

This method will work if you use the following code to redirect:

this.router.navigate(['./yourlocation', { user: this.user }]);

Modifed

Angular Url structure is a/:paras1/:paras2 or a?a=3; without using &.

If you use & to separate your parameters, it is recommended to use nativeJS to get.

constructor(){
  this.user = this.getUrlParameter('user');
}

public user;
private getUrlParameter(sParam) {
  return decodeURIComponent(window.location.search.substring(1)).split('&')
   .map((v) => { return v.split("=") })
   .filter((v) => { return (v[0] === sParam) ? true : false })
   .reduce((prev, curv, index, array) => { return curv[1]; }, undefined); 
};