【发布时间】:2016-12-12 02:00:18
【问题描述】:
我目前正在使用 Angular 2 tutorial 并学习如何使用带参数的路由器通过 id 获取对象数据。
以下是用于参考我将要问的问题的代码。
这是app.module.ts中的路由定义,用于根据id指向组件
{
path:'detail/:id',
component:HeroDetailComponent
}
基于id获取数据的服务方法(来自Service类)
getHero(id: number): Promise<Hero> {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
以及用于从 url 拉取信息的构造函数和 OnInit 方法(来自将显示数据的 hero-details.component)
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location
){}
ngOnInit():void{
this.route.params
.switchMap((params:Params) => this.heroService.getHero(+params['id'])
.subscribe(hero => this.hero = hero));
}
最后是我们要提取的数据的示例。id 是类型编号和名称类型字符串。
{ id: 11, name: 'Mr. Nice' }
问题:在ngOnInit 中,我们将id 从字符串转换为this.heroService.getHero() 调用参数中的数字。 +params['id'] 在转换方面究竟是如何工作的?我的猜测是,这是由于我们在 app.module.ts 文件中布置路线的方式,而 detail/:id 相当于 params['id'] 但我想要一个清晰的解释,以便我知道我在做什么未来。谢谢
【问题讨论】:
-
路由参数总是字符串,这取决于你想用这个参数做什么。
标签: angular typescript angular2-routing