十、路由和导航

在Angular中,路由是一个重要的模块,用于在应用程序中定义网址(URL)和它们对应的组件。Angular路由器(Router)管理从一个视图到另一个视图的导航,实现单页应用(SPA)的不同视图显示。

一路由的基本使用

    1. 在index.html 中添加 默认路径
    ini 复制代码
    <base href="/">
    1. 定义路由 : 路由的定义通常在应用模块中完成,通过RouterModule.forRoot(routes)方法注册。
    typescript 复制代码
    import { 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 {}
    1. 路由模块导入 : 通常,将路由配置在一个单独的模块AppRoutingModule中,并在主模块 AppModule中导入这个模块。
    python 复制代码
    import { 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 { }
    1. 在app.component.html 开始使用
    xml 复制代码
    <nav>
    <a routerLink="/home">Home</a>
    <a routerLink="/about">About</a>
    </nav>
    
    <router-outlet></router-outlet>

二 路由传参

query传参

  1. 导航时传递查询参数

使用[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 传参

  1. 设置路由
go 复制代码
在路由配置中使用`:`符号定义路径参数。例如:
ini 复制代码
```
const routes: Routes = [
  { path: 'product/:id', component: ProductDetailComponent }
];
```
  1. 导航时传递参数
css 复制代码
使用`[routerLink]`传递参数。

```
<a [routerLink]="['/product', productId]">View Product</a>
```    
  1. 在组件中接收参数
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']) 
 })
  }
}
```

三、 路由嵌套

  1. 设置主路由

在主路由设置中,引入一个组件,并为该组件定义一个子路由模块。

yaml 复制代码
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'admin', component: AdminComponent, children: [
    { path: 'users', component: UsersComponent },
    { path: 'settings', component: SettingsComponent }
  ]}
];
  1. 使用 <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>,用于展示其子路由对应组件的视图。

  2. 导航到嵌套路由

使用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');
}
}
相关推荐
Highcharts.js26 分钟前
如何下载使用Highcharts Grid 开发web可编辑表格
前端·人工智能·grid 表格·web 表格·在线编辑表格·highcharts表格安装·表格开发工具
用户62960593247051 小时前
从“浏览器根本区分不了”到真正实现:刷新不退出,关闭标签页自动退出,前端判断浏览器关闭和刷新
前端
qetfw1 小时前
MWU:Vue 3 + FastAPI 的 MaaFramework 跨平台 WebUI 源码
前端·vue.js·python·fastapi·开源项目·效率工具
mfxcyh1 小时前
Vue3+Ant Design Vue 实现手动异步文件上传(含大小校验、弹窗上传)
前端·javascript·vue.js
wordbaby1 小时前
Web端热敏标签打印完整解决方案(QZ Tray + 译维A42)
前端
swipe1 小时前
03|Axios 请求进了后端之后:Controller、Request、Response 是怎么接住它的?
前端·后端·全栈
meilindehuzi_a1 小时前
Vue3进阶基础:指令修饰符、v-model表单绑定、动态样式、计算属性与侦听器实战
前端·javascript·vue.js
csdn2015_1 小时前
vue 前端运行命令
前端·javascript·vue.js
swipe1 小时前
02|从 `pnpm dev` 到 Spring Boot 启动:后端服务到底怎么跑起来?
前端·后端·全栈
swipe2 小时前
01|前端人第一次打开 Spring Boot 项目,应该先看哪里?
前端·后端·全栈