深度玩家可移步Angular - 常见路由任务
1、嵌套路由
const routes: Routes = [
{
path: 'first',
component: FirstComponent,//同步加载
//这就是嵌套路由↓
children:[
{path:'first-sub1',component:firstSub1Component},
{path:'first-sub2',component:firstSub2Component},
]
},
];
深度玩家可移步Angular - Router
2、路由跳转
<!--在html标签上加跳转-->
<a routerLink="../second-component">Relative Route to second component</a>
import { Router } from '@angular/router';
constructor(private router: Router) { }
//各种跳转方式
this.router.navigate(['items'], { relativeTo: this.route });
this.router.navigateByUrl("/team/33/user/11");
this.router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
this.router.navigate(['team', 33, 'user', 11], {relativeTo: route});
this.router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
3、路由传参
//1.以根路由跳转/login
this.router.navigate(['login']);
//2.设置relativeTo相对当前路由跳转,route是ActivatedRoute的实例,使用需要导入ActivatedRoute
this.router.navigate(['login', 1],{relativeTo: route});
//3.路由中传参数 /login?name=1
this.router.navigate(['login', 1],{ queryParams: { name: 1 } });
//4.preserveQueryParams默认值为false,设为true,保留之前路由中的查询参数/login?name=1 to /home?name=1
this.router.navigate(['home'], { preserveQueryParams: true });
//5.路由中锚点跳转 /home#top
this.router.navigate(['home'],{ fragment: 'top' });
//6.preserveFragment默认为false,设为true,保留之前路由中的锚点/home#top to /role#top
this.router.navigate(['/role'], { preserveFragment: true });
//7.skipLocationChange默认为false,设为true,路由跳转时浏览器中的url会保持不变,但是传入的参数依然有效
this.router.navigate(['/home'], { skipLocationChange: true });
//8.replaceUrl默认为true,设为false,路由不会进行跳转
this.router.navigate(['/home'], { replaceUrl: true });
4、路由参数获取
import { ActivatedRoute } from '@angular/router';
constructor( private route: ActivatedRoute ) {}
//第一种:在查询参数中传递数据----------------------------------------
//在路由中传递
{path:"address/:id"} => address/1 => ActivatedRoute.param.id
//点击事件传递
<a [routerLink] = "['/address',1]">
//在不同等级页面跳转可以用snapshot(快照方式)
this.route.snapshot.params.id
this.route.snapshot.queryParams.id
//相同组件跳转需要使用subscribe(订阅方式)
this.route.params.subscribe((params: Params) => this.id = params.id )
//第二种:在路由路径中传递参数数据----------------------------------------
<a [routerLink] = "['/address']" queryParams= "{id:1}">
this.route.snapshot.queryParams.id//拿到路由中的参数(即浏览器网页地址中url后面的?参数=)
//第三种:在路由配置中传递数据----------------------------------------
{path:'home', component: HomeComponent,data:[{isPush:true}] }
=>
ActivatedRoute.data[0][isPush]
//同样也是有snapshot和subscribe两种类型
this.route.snapshot.data[0]['isPush']