Get route query params

izupet picture izupet · Jul 20, 2016 · Viewed 73.7k times · Source

I am trying to migrate from rc1 to rc4 and i have trouble getting query string parameters. ActivatedRoute object always empty.

hero.component.ts

import {Component, OnInit} from "@angular/core";
import {Control} from "@angular/common";
import {ROUTER_DIRECTIVES, ActivatedRoute} from '@angular/router';

@Component({
    template: '../partials/main.html',
    directives: [ROUTER_DIRECTIVES]
})

export class HeroComponent implements OnInit {

    constructor(private _activatedRoute: activatedRoute) {

    }

    ngOnInit() {
        this._activatedRoute.params.subscribe(params => {
            console.log(params);
        });
    }
}

main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS, RequestOptions, Http} from '@angular/http';
import {AppRouterProviders} from './app.routes';

bootstrap(AppComponent, [
    AppRouterProviders,
    HTTP_PROVIDERS
]);

app.component.ts

import {Component, OnInit} from '@angular/core';
import {HeroComponent} from './hero.component';
import {RouteConfig, Router, ROUTER_DIRECTIVES} from '@angular/router';


@Component({
    selector: 'my-app',
    templateUrl: '../partials/main.html',
    directives: [
        HeroComponent,
        ROUTER_DIRECTIVES
    ]
})

export class AppComponent {
}

partials/main.html

<a class="nav-link" [routerLink]="['/']" [queryParams]="{st: 'new'}">New</a>

app.routes.ts

import {provideRouter, RouterConfig}  from '@angular/router';
import {HeroComponent} from './hero.component';
import {ErrorComponent} from './error.component';

const routes: RouterConfig = [
    {path:'', component: HeroComponent},
    {path:'**', component: ErrorComponent}
];

export const AppRouterProviders = [
    provideRouter(routes)
];

When i click on link 'New' console prints out empty object

Object {}

Updated

plunker

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jul 25, 2016

update (2.0.0 final)

(somepath/:someparam/someotherpath) you can subscribe to them using _router.queryParams.subscribe(...):

export class HeroComponent implements OnInit {
  constructor(private _activatedRoute: ActivatedRoute, private _router:Router) {
    _activatedRoute.queryParams.subscribe(
      params => console.log('queryParams', params['st']));

original

If you want queryParams instead of route params (somepath/:someparam/someotherpath) you can subscribe to them using _router.routerState.queryParams.subscribe(...):

export class HeroComponent implements OnInit {
  constructor(private _activatedRoute: ActivatedRoute, private _router:Router) {
    _router.routerState.queryParams.subscribe(
      params => console.log('queryParams', params['st']));

Plunker example