[Angular2 Router] Use Params from Angular 2 Routes Inside of Components

本文介绍如何使用Angular2中的ActivatedRoute获取当前路由的详细信息。通过将参数作为流提供,可以轻松地从流中映射所需的参数并在模板中显示。以HerosComponent为例,展示了如何配置路由并获取路由参数。

Angular 2’s ActivatedRoute allows you to get the details of the current route into your components. Params on the ActivatedRoute are provided as streams, so you can easily map the param you want off of the stream and display it in your template.

 

For example we have a HerosComonent, and inside HerosComponent, we will have multi HeroComponent:

heros.component.html:

<ul>
  <li>
    <a [routerLink]="'1'"
       routerLinkActive="active"
       [routerLinkActiveOptions]="{exact: true}">Hero 1</a>
  </li>
</ul>

heros.routers.ts:

import {HerosComponent} from "./heros.component";
import {RouterModule} from "@angular/router";
import {HeroComponent} from "./hero/hero.component";
const routes = [
  {path: '', component: HerosComponent},
  {path: ':id', component: HeroComponent},
];
export default RouterModule.forChild(routes)

hero.component.ts:

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";

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

  id;
  constructor(private router: ActivatedRoute) {
    this.id = router.params.map((p:any) => p.id);
  }

  ngOnInit() {
  }

}

 

Github

转载于:https://www.cnblogs.com/Answer1215/p/5907782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值