How to get query parameters from URL in Angular 5? How to get query parameters from URL in Angular 5? angular angular

How to get query parameters from URL in Angular 5?


In Angular 5, the query params are accessed by subscribing to this.route.queryParams (note that later Angular versions recommend queryParamMap, see also other answers).

Example: /app?param1=hallo&param2=123

param1: string;param2: string;constructor(private route: ActivatedRoute) {    console.log('Called Constructor');    this.route.queryParams.subscribe(params => {        this.param1 = params['param1'];        this.param2 = params['param2'];    });}

whereas, the path variables are accessed by this.route.snapshot.params

Example: /param1/:param1/param2/:param2

param1: string;param2: string;constructor(private route: ActivatedRoute) {    this.param1 = this.route.snapshot.params.param1;    this.param2 = this.route.snapshot.params.param2;}


This is the cleanest solution for me

import { Component, OnInit } from '@angular/core';import { ActivatedRoute } from '@angular/router';export class MyComponent {  constructor(    private route: ActivatedRoute  ) {}  ngOnInit() {    const firstParam: string = this.route.snapshot.queryParamMap.get('firstParamKey');    const secondParam: string = this.route.snapshot.queryParamMap.get('secondParamKey');  }}


I know that OP asked for Angular 5 solution, but yet for all of you who stumbles upon this question for newer (6+) Angular versions. Citing the Docs, regarding ActivatedRoute.queryParams (which most of other answers are based on):

Two older properties are still available. They are less capable thantheir replacements, discouraged, and may be deprecated in a futureAngular version.

params — An Observable that contains the required and optionalparameters specific to the route. Use paramMap instead.

queryParams — An Observable that contains the query parameters availableto all routes. Use queryParamMap instead.

According to the Docs, the simple way to get the query params would look like this:

constructor(private route: ActivatedRoute) { }ngOnInit() {    this.param1 = this.route.snapshot.paramMap.get('param1');    this.param2 = this.route.snapshot.paramMap.get('param2');}

For more advanced ways (e.g. advanced component re-usage) see this Docs chapter.

EDIT:

As it correctly stated in comments below, this answer is wrong - at least for the case specified by OP.

OP asks to get global query parameters (/app?param1=hallo&param2=123); in this case you should use queryParamMap (just like in @dapperdan1985 answer).

paramMap, on the other hand, is used on parameters specific to the route (e.g. /app/:param1/:param2, resulting in /app/hallo/123).

Thanks to @JasonRoyle and @daka for pointing it out.