Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 4 how to get url parameters

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.

like image 872
Autorun Avatar asked Nov 03 '17 01:11

Autorun


People also ask

How do I find the parameter of a URL?

For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object. By using Separating and accessing each parameter pair.

What is Parammap in Angular?

ParamMaplink A map that provides access to the required and optional parameters specific to a route. The map supports retrieving a single value with get() or multiple values with getAll() .


6 Answers

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); 
};
like image 124
Rach Chen Avatar answered Oct 12 '22 09:10

Rach Chen


If you want to use query params and not define them in route, you can reference ActivatedRoute in your constructor and subscribe to queryParams.

constructor(private route: ActivatedRoute) {
    this.route
      .queryParams
      .subscribe(params => {
          // here you can access params['user'], params['token'], etc.
      });
}
like image 30
Vitalii Chmovzh Avatar answered Oct 12 '22 09:10

Vitalii Chmovzh


By using ActivatedRoute snapshot as below example.

this.userName = this.activatedRoute.snapshot.params['user'];
this.userToken = this.activatedRoute.snapshot.params['token'];
this.userPicture = this.activatedRoute.snapshot.params['picture'];
like image 42
i3lai3la Avatar answered Oct 12 '22 11:10

i3lai3la


Want to know all url parameters?

constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe((params: Params) => {
       console.log(params)
    })
}

In child route, you need to use parent to get parent-route parameters

this.activatedRoute.parent.params.subscribe((params: Params) => {
    console.log(params)
})
like image 21
WasiF Avatar answered Oct 12 '22 10:10

WasiF


Double check to make sure you defined the routes properly.

In your route definition you should have something like this:

path: ':user/:id/:token/:picture'

like image 37
pfcodes Avatar answered Oct 12 '22 09:10

pfcodes


To get url parameters in angular 4 eg:http://localhost/doctor?test=1

import {Component} from '@angular/core';
import {Router} from '@angular/router';
@Component({
  selector: 'app-root',
  templateUrl: './app.home.html',
})

export class HomeComponant {
title = 'Home';


constructor(

    private router: Router,

) {}

onSubmit() {
  this.router.navigate(['/doctor'],{queryParams:{test:1}});
}

}

like image 27
Krishnamoorthy Acharya Avatar answered Oct 12 '22 11:10

Krishnamoorthy Acharya