在Angular中,路由是一个重要的模块,用于在应用程序中定义网址(URL)和它们对应的组件。Angular路由器(Router)管理从一个视图到另一个视图的导航,实现单页应用(SPA)的不同视图显示。
一路由的基本使用
-
- 在index.html 中添加 默认路径
ini<base href="/"> -
- 定义路由 : 路由的定义通常在应用模块中完成,通过
RouterModule.forRoot(routes)方法注册。
typescriptimport { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // 默认路由 重定向 { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: '**', component: HomeComponent } // 404路由 ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} - 定义路由 : 路由的定义通常在应用模块中完成,通过
-
- 路由模块导入 : 通常,将路由配置在一个单独的模块
AppRoutingModule中,并在主模块AppModule中导入这个模块。
pythonimport { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } - 路由模块导入 : 通常,将路由配置在一个单独的模块
-
- 在app.component.html 开始使用
xml<nav> <a routerLink="/home">Home</a> <a routerLink="/about">About</a> </nav> <router-outlet></router-outlet>
二 路由传参
query传参
- 导航时传递查询参数
使用[queryParams]传递参数。 <a [routerLink]="['/products']" [queryParams]="{ category: 'electronics' }">View Electronics</a> 2. 在组件中接收查询参数
kotlin
使用`ActivatedRoute`服务获取查询参数。
```
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
const category = params['category'];
console.log(category);
});
this.route.snapshot.queryParamMap.get('category') //快照方式
}
}
```
parameter 传参
- 设置路由
go
在路由配置中使用`:`符号定义路径参数。例如:
ini
```
const routes: Routes = [
{ path: 'product/:id', component: ProductDetailComponent }
];
```
- 导航时传递参数
css
使用`[routerLink]`传递参数。
```
<a [routerLink]="['/product', productId]">View Product</a>
```
- 在组件中接收参数
kotlin
使用`ActivatedRoute`服务获取参数。
```
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html'
})
export class ProductDetailComponent implements OnInit {
productId: string;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.productId = this.route.snapshot.paramMap.get('id');
this.route.params.subscribe(params => {
console.log(params['id'])
})
}
}
```
三、 路由嵌套
- 设置主路由
在主路由设置中,引入一个组件,并为该组件定义一个子路由模块。
yaml
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'admin', component: AdminComponent, children: [
{ path: 'users', component: UsersComponent },
{ path: 'settings', component: SettingsComponent }
]}
];
-
使用
<router-outlet>指令在父组件的模板中插入
<router-outlet>指令,以加载子路由的组件。xml<!-- admin.component.html --> <h2>Admin Section</h2> <nav> <a routerLink="users">Users</a> <a routerLink="settings">Settings</a> </nav> <router-outlet></router-outlet>在
AdminComponent里使用<router-outlet>,用于展示其子路由对应组件的视图。 -
导航到嵌套路由
使用routerLink来导航至子路由路径。
xml
```
<!-- 在父组件中,例如 dashboard.component.html -->
<a routerLink="/admin">Admin Section</a>
<a routerLink="/admin/users">Manage Users</a>
```
四、编程式路由导航
- 1 方式一使用
navigate方法
typescript
import { Router } from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
constructor(private router: Router) {}
goToUserDetail(userId: number) {
this.router.navigate(['/user', userId]);
}
}
- 2 方式二使用
navigateByUrl方法
typescript
import { Router } from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
constructor(private router: Router) {}
goToHome() {
this.router.navigateByUrl('/home');
}
}