十、路由和导航

在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');
}
}
相关推荐
asing11 小时前
🤯 为什么我的收银台在鸿蒙系统“第一次返回”死活拦不住?一次差点背锅的排查实录
前端·harmonyos
德育处主任11 小时前
『NAS』在群晖部署图片压缩工具-Squoosh
前端·javascript·docker
Hao_Harrision11 小时前
50天50个小项目 (React19 + Tailwindcss V4) ✨| ThreeDBackgroundBoxes(3D背景盒子组件)
前端·3d·typescript·react·tailwindcss·vite7
加个鸡腿儿11 小时前
经验分享2:SSR 项目中响应式组件的闪动陷阱与修复实践
前端·css·架构
心.c11 小时前
如何基于 RAG 技术,搭建一个专属的智能 Agent 平台
开发语言·前端·vue.js
智航GIS11 小时前
10.7 pyspider 库入门
开发语言·前端·python
华仔啊12 小时前
写 CSS 用 px?这 3 个单位能让页面自动适配屏幕
前端·css
静听松涛13312 小时前
提示词注入攻击的防御机制
前端·javascript·easyui
晚风予星12 小时前
简记 | 一个基于 AntD 的高效 useDrawer Hooks
前端·react.js·设计
栗子叶12 小时前
网页接收服务端消息的几种方式
前端·websocket·http·通信