如何在Angular2 rc5中获得Route Params?

时间:2016-10-24 13:40:12

标签: javascript php jquery html angular

我使用Angular2 RC5通过路由器获取一个简单的参数。该参数只是一个名称。在app.routes.ts中,我将route参数设置为“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}}

每当我访问http://localhost:4200/directory/richard时,它都会将我重定向到ROOT网址。理查德是忍者的名字。

它应该在directory.component.ts

中显示忍者的名字

1 个答案:

答案 0 :(得分:2)

1)导入

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

2)构造函数

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

3)订阅

this.route.params.subscribe(params => {
  console.log('Param whatever: ', params['whatever']);
  this.whatever = params['whatever'];
});