碎碎念:知识点梳理归纳,如果有什么不对的感谢大家指正一起学习!
一、路由相关对象介绍:
对象名称 | 简介 |
---|---|
Routes | 配置路由,保存着哪个URL对应展示哪个组件 |
RouterOutlet | 在html中标记路由内容呈现位置的占位符指令。 |
Router | 负责在运行时执行路由的对象,可以通过调用其navigate |
RouterLink | 在html声明路由导航用的指令。 |
ActivatedRoute | 当前激活的路由对象,保存着当前路由信息,如路由地址,路由参数等。 |
1. RouterLink
使应用链接到特定组件
/根路由 ./子路由
// / 对应当前routing中路由配置的根路由
<a [routerLink]="[/]"></a>
<a [routerLink]="[./home]"></a>
2. RouterOutlet
一个占位符,路由跳转时angular会查找当前匹配组件将组件插入到RouterOutlet中
3. RouterLinkActive
在当前路径与元素链接匹配时为元素添加css样式
二、路由参数传递
在路由时传递数据三种方法
- 在查询参数中传递数据
ActivatedRoute.queryParams[id] - 在路由路径中传递数据
ActivatedRoute.params[id] - 在路由配置中传递数据
data:[{ }]
1. 在查询参数中传递数据
<a [routerLink]="[ '/product']" [queryParams]="{id:1}">product</a>
// 获取参数
productId: number;
this.productId = this.activatedRoute.snapshot.queryParams["id"]
2. 在URL中传递参数,三步:
2.1.修改路由中的path属性,使其可以携带参数
{
path: 'product/:id',
component: ProductComponent
}
2.2 修改路由链接的参数
// html
<a [routerLink]="[ '/product',1]">product</a>
2.3 修改获取参数属性
( snapshot和参数订阅 )
// ts
export class ProductComponent implements OnInit {
productId: number;
constructor(
private activatedRoute: ActivatedRoute
) { }
ngOnInit() {
this.productId = this.activatedRoute.snapshot.params["id"];
}
}
参数快照 snapshot
组件在没有被重新创建时,路由的id会变,但是页面上的值不会被重新赋值
(从home组件到商品详情1/2的时候组件会被重新创建,走ngOnInit方法,重新赋值,商品详情1-2的时候不会被创建而重新赋值)
参数订阅
export class ProductComponent implements OnInit {
productId: number;
constructor(
private activatedRoute: ActivatedRoute
) { }
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => this.productId = params["id"]);
}
}
3. 在路由配置中传递数据
- 在路由配置里,目标组件后边,添加数据data,data是一个数组
// routing
path: 'product/:id', component: ProductComponent, data: [{ isPro: true }],
- 代码接收data里的数据
export class ProductComponent implements OnInit {
isPro: boolean;
constructor(
private activatedRoute: ActivatedRoute
) { }
ngOnInit() {
this.isPro=this.activatedRoute.snapshot.data[0]['isPro']
}
}
效果预览:
三、其他知识点
1. 重定向路由
在用户访问一个特定的地址时,将其重定向到另一个指定的地址
例:
www.baidu.com => ww.baidu.com/list
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent}
当访问是空字符串的时候,当前路由重定向到home路由上
四、 子路由
4.1 普通路由
普通路由语法
{path: 'home', component: HomeComponent}
4.2 子路由
子路由语法
语法:children:[{ }]
{
path: 'home', component: HomeComponent,
children: [
{path: '', component: xxxcomponent },
{path: '/yyy', component: yyycomponent }
]
}
五、辅助路由
激活后,在任何页面都会显示相关的辅助路由组件。
三步
5.1 在主插座的旁边声明一个带‘name’属性的插座
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
5.2 在路由配置里面配置名字叫‘aux’可以显示哪个组件
// ChatComponent,新建的聊天组件
{ path: 'chat', component: ChatComponent, outlet: 'aux' }
5.3 通过路由的配置和路由的参数决定聊天组件是否显示
// aux 路由的路由是chat
<a [routerLink]="[{outlets:{aux:'chat'}}]">开始聊天</a>
<a [routerLink]="[{outlets:{aux:null}}]">结束聊天</a>
效果预览:
primary属性:制主路由
在展示chart聊天组件的时候,主路由跳到home路径上
(不管在哪个页面上,点开始聊天就跳到home路径上)
<a [routerLink]="[{outlets:{primary:'home',aux:'chat'}}]">开始聊天</a>
<a [routerLink]="[{outlets:{aux:null}}]">结束聊天</a>
效果预览:
总结:注意添加主路由后,url的变化