How to get Route Params in Angular2 rc5?

69 views
Skip to first unread message

berengu...@gmail.com

unread,
Oct 24, 2016, 11:26:43 AM10/24/16
to Angular

I am getting a simple parameter via the router, using Angular2 RC5. The parameter is just a name. In app.routes.ts, I set the route parameter to "directory/:ninja".

app.routes.ts
import { Routes, RouterModule } from "@angular/router";
import { DirectoryComponent } from "./directory/directory.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [

{ path: 'directory/:ninja', component: DirectoryComponent },
{ path: '', component: HomeComponent }

];

export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);

directory.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-directory',
  templateUrl: './directory.component.html',
  styleUrls: ['./directory.component.css']
})
export class DirectoryComponent implements OnInit {

  ninja: string;    

  constructor(public route: ActivatedRoute) { 

    this.ninja = route.snapshot.params['ninja'];

  }

  ngOnInit() {
  }

}

directory.component.html
{{ninja}}

Whenever I access http://localhost:4200/directory/richard, it redirects me to the ROOT URL. Richard is the name of the ninja.

It should display the name of the ninja in directory.component.ts


Please help

Nick Bachicha

unread,
Oct 25, 2016, 2:58:07 PM10/25/16
to Angular
You need to subscribe to the route parameters. You should also move the assignment out of the constructor and into the ngOnInit

export class DirectoryComponent implements OnInit, OnDestroy  {

  ninja: string;    
  subscription: any;

  constructor(public route: ActivatedRoute) {}

  ngOnInit() {
  this.subscription = this.route.params.subscribe(params =>{
  this.ninja = params['ninja'];
  });
  }

  ngOnDestroy(): void {
  this.subscription.unsubscribe();
  }
}
Reply all
Reply to author
Forward
0 new messages