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.