How to get query params from url in Angular 2?

By injecting an instance of ActivatedRoute one can subscribe to a variety of observables, including a queryParams and a params observable:

import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';

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

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
    this.activatedRoute.queryParams.subscribe(params => {
        const userId = params['userId'];
        console.log(userId);
      });
  }

}

A NOTE REGARDING UNSUBSCRIBING

@Reto and @codef0rmer had quite rightly pointed out that, as per the official docs, an unsubscribe() inside the components onDestroy() method is unnecessary in this instance. This has been removed from my code sample. (see blue alert box in this tutorial)

Leave a Comment