How to get query params from url in Angular 2?

FireGM picture FireGM · Feb 28, 2016 · Viewed 333.8k times · Source

I use angular2.0.0-beta.7. When a component is loaded on a path like /path?query=value1 it is redirected to /path. Why were the GET params removed? How can I preserve the parameters?

I have an error in the routers. If I have a main route like

@RouteConfig([
  {
      path: '/todos/...',
      name: 'TodoMain',
      component: TodoMainComponent
  }
])

and my child route like

@RouteConfig([
  { path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
  { path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])

then I can't get params in TodoListComponent. I am able to get

params("/my/path;param1=value1;param2=value2") 

but I want the classic

query params("/my/path?param1=value1&param2=value2")

Answer

Stephen Paul picture Stephen Paul · Aug 25, 2016

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)