Get route query params
Asked Answered
A

4

32

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

Australoid answered 20/7, 2016 at 18:50 Comment(0)
S
72

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

Straus answered 25/7, 2016 at 4:58 Comment(9)
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.Australoid
I don't understand your question. What do you mean with "empty"? ActivatedRoute is passed in, otherwise .params.subscribe() would throw.Hyperform
The ActivatedRoute itself should contain query params about activated component but i get empty object when I subscribe . Dont know how to clarify better.Australoid
Can you please post an updated Plunker with a console.log(...) that prints the empty object you're talking about?Hyperform
My plunker example can already shows you this. Check plnkr.co/edit/s5tYzWmbOXZRiRdunF4N?p=preview and open the console and see the output.Australoid
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.Hyperform
It seems RouterState does no longer have a property queryParams angular.io/docs/ts/latest/api/router/index/…Abbe
Thanks @CarloRoosen. _activatedRoute.queryParams.subscribe or _activatedRoute.snaphsot.queryParams provide queryParams now.Hyperform
@GünterZöchbauer Did you solve the initial params issue?Fishwife
T
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.

Tanka answered 13/5, 2017 at 21:30 Comment(0)
C
2

You also can get params using one line of code.

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


this.route.snapshot.paramMap.get('id');
Cybernetics answered 12/10, 2022 at 3:56 Comment(0)
M
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);
       });
Mcgriff answered 20/7, 2016 at 19:5 Comment(8)
I tried this before but getting undefined when trying to get query string parameter. params is actually empty object.Australoid
is this how you pass the parameter? onSelect(hero: Hero) { this.router.navigate(['/hero', hero.id]); }Mcgriff
this way [routerLink]="['/']" [queryParams]="{st: 'rec'}" I want to get st paramAustraloid
Then try the new way. you should really read this section on the docs.Mcgriff
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 } ];Mcgriff
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.Mcgriff
Let us continue this discussion in chat.Mcgriff
There is a difference between params and queryParams. params is like url.com/id and query params is like url.com?id=4Melquist

© 2022 - 2024 — McMap. All rights reserved.