30

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
izupet
  • 1,529
  • 5
  • 20
  • 42

4 Answers4

70

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    I like your answer and it works as expected, but you maybe know why did I get empty ActivatedRoute object in my plunker example? Just curious. – izupet Jul 25 '16 at 16:03
  • I don't understand your question. What do you mean with "empty"? `ActivatedRoute` is passed in, otherwise `.params.subscribe()` would throw. – Günter Zöchbauer Jul 28 '16 at 05:42
  • The ActivatedRoute itself should contain query params about activated component but i get empty object when I subscribe . Dont know how to clarify better. – izupet Jul 28 '16 at 06:46
  • Can you please post an updated Plunker with a `console.log(...)` that prints the empty object you're talking about? – Günter Zöchbauer Jul 28 '16 at 06:49
  • My plunker example can already shows you this. Check http://plnkr.co/edit/s5tYzWmbOXZRiRdunF4N?p=preview and open the console and see the output. – izupet Jul 28 '16 at 06:55
  • 1
    But there is no parameter on initial load. You Plunker doesn't use `params` at all. The `New` link uses `queryParams` but that is only passed after the link is clicked. – Günter Zöchbauer Jul 28 '16 at 06:58
  • 1
    It seems RouterState does no longer have a property queryParams https://angular.io/docs/ts/latest/api/router/index/RouterState-interface.html – Carlo Roosen Dec 19 '16 at 12:18
  • Thanks @CarloRoosen. `_activatedRoute.queryParams.subscribe` or `_activatedRoute.snaphsot.queryParams` provide `queryParams` now. – Günter Zöchbauer Dec 19 '16 at 12:22
  • @GünterZöchbauer Did you solve the initial params issue? – huan feng Dec 07 '18 at 03:18
9

I was struggling with the same problem for a long time. The answer is tricky, in the documentation it was stated:

ActivatedRoute: A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params, and the global fragment. This is mentioned in here

The trick answer is 'route component', that means ActivatedRoute will work only on components that are routed. In other words only components described in the routing table.

> Reading the obfuscating official documentation here. It mentions 'route associated with a component loaded in an outlet'. We can only guess what is an outlet...

I wrote a little investigative code to research this problem in stand alone app.module.ts:

import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'comp1',
  template: `<h4>comp1 works</h4>`,
})
export class Comp1 { }

@Component({
  selector: 'comp2',
  template: `<h4>comp2 works</h4>`,
})
export class Comp2 { }

@Component({
  selector: 'fail',
  template: `<div>Wrong URL:{{url | json}}</div> <h4>Failure page works</h4>`,
})
export class Fail {
  private url: any;
  constructor(public activeRoute: ActivatedRoute) {
    this.url = activeRoute.snapshot.url
  };

}

@Component({
  selector: 'app-root',
  template: `<div>Base URL:{{url | json}}</div> <router-outlet></router-outlet>`,
})
export class App {
  private url: any;
  constructor(public activeRoute: ActivatedRoute) {
    this.url = activeRoute.snapshot.url
  };
}

const appRoutes: Routes = [
  { path: '1', component: Comp1 },
  { path: '2', component: Comp2 },
  { path: '**', component: Fail }
];

@NgModule({
  imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
  declarations: [App, Comp2, Comp1, Fail],
  bootstrap: [App]
})
export class AppModule { }

Try running the module for the following URI:

Good luck, hope the code is demonstrative.

Dudi Boy
  • 4,551
  • 1
  • 15
  • 30
2

You also can get params using one line of code.

constructor(
private router: Router,
private route: ActivatedRoute,
) { }


this.route.snapshot.paramMap.get('id');
sumanta.k
  • 498
  • 1
  • 8
  • 26
1

check angular documentation, its all there: https://angular.io/docs/ts/latest/guide/router.html

constructor(
  private route: ActivatedRoute,
  private router: Router,
  private service: HeroService) {}

    ngOnInit() {
      this.sub = this.route.params.subscribe(params => {
         let id = +params['id']; // (+) converts string 'id' to a number
         this.service.getHero(id).then(hero => this.hero = hero);
       });
Avi
  • 1,924
  • 3
  • 17
  • 31
  • 1
    I tried this before but getting undefined when trying to get query string parameter. params is actually empty object. – izupet Jul 20 '16 at 19:17
  • is this how you pass the parameter? onSelect(hero: Hero) { this.router.navigate(['/hero', hero.id]); } – Avi Jul 20 '16 at 19:20
  • this way [routerLink]="['/']" [queryParams]="{st: 'rec'}" I want to get st param – izupet Jul 20 '16 at 19:24
  • Then try the new way. you should really read this section on the docs. – Avi Jul 20 '16 at 19:26
  • maybe this is your missing part, check the id param in the hero route: export const heroesRoutes: RouterConfig = [ { path: 'heroes', component: HeroListComponent }, { path: 'hero/:id', component: HeroDetailComponent } ]; – Avi Jul 20 '16 at 19:31
  • you are clearly missing something. please post all the relevant code, or finish this tutorial. I can assure you it's working great for me. – Avi Jul 20 '16 at 19:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117851/discussion-between-avi-and-izupet). – Avi Jul 20 '16 at 21:00
  • There is a difference between params and queryParams. params is like url.com/id and query params is like url.com?id=4 – Brian Davis May 04 '20 at 18:12