How to get query parameters from URL in Angular 5?

Lars picture Lars · Nov 23, 2017 · Viewed 339.2k times · Source

I'm using angular 5.0.3, I would like to start my application with a bunch of query parameters like /app?param1=hallo&param2=123. Every tip given in How to get query params from url in Angular 2? does not work for me.

Any ideas how to get query parameters work?

private getQueryParameter(key: string): string {
  const parameters = new URLSearchParams(window.location.search);
  return parameters.get(key);
}

This private function helps me to get my parameters, but I don't think it is the right way in new Angular environment.

[update:] My main app looks like

@Component({...})
export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    // would like to get query parameters here...
    // this.route...
  }
}

Answer

Vijayendra Mudigal picture Vijayendra Mudigal · Jan 6, 2018

In Angular 5, the query params are accessed by subscribing to this.route.queryParams.

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;
}