0

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

redshot
  • 2,930
  • 3
  • 31
  • 68
  • http://stackoverflow.com/questions/34597835/how-to-get-current-route/40115938#40115938 –  Oct 24 '16 at 13:48

1 Answers1

2

1) Import

import {ActivatedRoute} from '@angular/router';

2) Constructor

constructor(private route:ActivatedRoute,.......

3) Subscribe

this.route.params.subscribe(params => {
  console.log('Param whatever: ', params['whatever']);
  this.whatever = params['whatever'];
});
  • Thanks for your answer. However, i am still not able to get the parameter to the component. – redshot Oct 24 '16 at 13:59
  • cay you put it into plnkr? you can take this one as angular2-basis: http://plnkr.co/edit/XXeu7zi0ULY6sfdw6MYc –  Oct 24 '16 at 13:59