angular路由
1)路由基础
|名称|简介 |
|-Routes-|-路由配置,有path,component两个属性-|
| RouterOutlet |在Html中展示内容的占位符 |
|Router|在运行时执行路由的对象,有navigator方法 |
|-RouterLink-|-路由连接-|
|-ActivatedRoute-|-当前**的路由对象,可以保存传递的参数 -|
1)定义组件,配置路由
//创建项目
ng new Demo --routing
//创建组件
ng g m home --routing
ng g c home
ng g s home
//配置路由app-routing文件中(使用通配符配置,用于识别不存在的路由,一般放在最后,由于路由优先的原则)
(1):引入组件:import {HomeComponent};import {ProductComponent};import {ErrorCodeCOmponent};
const Routes=[
{path: ' ',component:HomeComponent},
{path:'product',component:ProductComponent},
{path:'**',component:ErrorCodeComponent}
]
(这里配置路由path时不能用/)
2)a标签链接
app.html
1)页面跳转的方法1
<a [routerLink]="['/']">跳转到home主页</a>
<a [routerLink]="['/product']">跳转到product主页</a>
<router-outlet></router-outlet>
(这里使用routerLink配置路由时要有/,用来判断是子路由还是主路由)
2)页面跳转的方法2
<button stype="button" (click)="toProduct()">跳转到商品页面</button>
<router-outlet></router-outlet>
在app.component中定义toProduct()
export class AppComponent{
constructor(private router:Router){}
toProduct(){
this.router.navigate(['/product']);//是数组形式
}
}
路由链接市值都是数组形式,用于传参
2)路由传参
(1)方法1/product?id=1&name=tom
在目标路由中–>ActivatedRoute.queryParams['id']
(2)方法2{path:/product/:id}
在目标路由中----->ActivatedRoute.params['id']
1)修改路由参数,使其可以传递参数
2)路由传参
3)目标组件中调用
(3)方法3{path:/product,component:ProductComponent,data:[{isProd:true}]}
在目标路由中 ---->
ActivatedRoute.data[0][isProd]
4)路由快照(snapshot)和路由订阅(subscribe)的区别