Angular 路由
路由是连接组件的, 它是树形结构的, 可以使用它在 angular 中实现路径的导航模式
可以将路由看成是一组规则, 它决定了url的变化对应着哪一种状态, 具体表现就是不同视图的切换, 在 Angular 中, 路由时非常重要的组成部分, 组件的实例化与销毁, 模块的加载, 组件的生命周期钩子的发起都与它有关.
路由的基本使用
路由器是一个调度中心, 它是一套规则的列表, 能偶查询当前 URL 对应的规则, 并展示出相应的视图
路由是列表里面的一个规则, 即路由定义, 它有很多功能字段
- path字段, 表示该路由中的URL路径部分
- Component字段, 表示与该路由相关联的操作
每个带路由的 Angular 应用都有一个路由器服务的单例对象, 通过路由定义的列表进行配置后使用
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
// 路由配置
const routes: Routes = [
{
// 此处实现默认进到应用中就进入 HomeComponent 组件
path: '',
component: HomeComponent
},
{
path: 'home',
component: HomeComponent
},
{
// 使用通配符进行匹配路由
path: '**',
component: HomeComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在 HTML 中需要使用 router-outlet 去显示路由中的内容, 类似于 Vue 中的router-view
<span>{{ title }} app is running!</span>
<!-- 第一个参数填写要跳转的路径, 第二个参数是如果当前路由是要跳转的路由, 就会给当前的 a 添加一个类 "router-link-active" -->
<a [routerLink]="['/home']" routerLinkActive="router-link-active">首页</a>
<router-outlet></router-outlet>
上述具体的工作流程, 可以描述为
- 当浏览器地址栏的 URL 变化时, 路径部分 /home 满足了列表中的 path 为 home 的这个路由定义, 激活了对应的实例, 显示视图
路由的嵌套
父子路由嵌套配置
app-routing.module.ts
{
path: 'parent',
component: HomeComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
记得需要在 HomeComponent 中同样加上 router-outlet 就可以了, 注意在跳转到子路由时候, 需要加上全路径
路由传参
query
在 a 标签上添加一个参数 queryParams, 并通过 this.routerinfo.snapshot.queryParams 获取参数
query 形式的传参会显示的路由URL上
<a [routerLink]="['/home']" [queryParams]="{id:3}">home</a>
在目标路由中可以接收参数
import { ActivateRoute } from '@angular/router';
constructor(private routerinfo:ActivateRoute) { }
ngOnInit() {
// id 为参数名字
this.id = this.routerinfo.snapshot.queryParams['id']
}
params
吸怪路由配置文件path, 路由导航a标签 routerLink 后面数组的第二个参数为传递到值, 并通过 subscribe 的方式获取 name 参数
{
path: 'home/:name',
component: HomeComponent
}
<a [routerLink]="['/home', '我是url传递的参数']" [queryParams]="{id:3}">home</a>
import { ActivateRoute } from '@angular/router';
constructor(private routerinfo:ActivateRoute) { }
ngOnInit() {
this.id = this.routerinfo.params.subscribe((params:Params) =>{
this.name = params['name']
})
}