路由跳转
路由跳转/导航:从一个路由跳转到另一个路由
实现方案:
方式1:使用模板方法
<any routerLink="/ucenter"></any>
注意:
- 可以用于任意标签上
- 跳转地址应该以/开头,防止以相对方式跳转 方式2:使用脚本跳转方法
注意:Router类是RouterModule提供的一个服务类,声明依赖即可
constructor(private router:Router){}
this.router.navigateByUrl('/ucenter')
路由传参
在路由词典中定义路由地址时,其中可以包含可变参数:
{path:'product/:id',component:...}
在路由跳转时可以为路由参数提供具体的参数值
<a routerLink="/product/5"></a>
到了目标路由组件,可以读取“当前路由地址”中的路由参数:
// 声明依赖:读取参数需要“当前的路由”服务对象
constructor(private route:ActivatedRoute){}
ngOnInit(){
// 组件初始化完成,读取路由参数,根据此参数查询路由详情
console.log('得到了订阅的路由参数',data);
this.route.params.subscribe(res=>{
console.log('得到了订阅的路由参数',res);
this.productId = res['lid']
})
}