十、路由和导航

在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');
}
}
相关推荐
五点六六六1 天前
你敢信这是非Native页面写出来的渐变效果吗🌝(底层原理解析
前端·javascript·面试
tedcloud1231 天前
TradingAgents部署教程:打造AI量化分析工作流
服务器·前端·人工智能·系统架构·edge
小村儿1 天前
连载10-Sub-agents 深度解析:从源码理解 Claude Code 的分身术
前端·后端·ai编程
IT_陈寒1 天前
Vite动态导入把我坑惨了,原来要这样用才对
前端·人工智能·后端
DFT计算杂谈1 天前
KPROJ编译教程
java·前端·python·算法·conda
觅_1 天前
前端学习后端的时候 选择一个技术
前端·学习
独泪了无痕1 天前
CryptoJS:数据安全的JavaScript加密利器
前端·vue.js·node.js
发现一只大呆瓜1 天前
一文搞懂 Vite 处理CommonJS包、按需编译逻辑及 Rollup 插件兼容规则
前端
Edwardwu1 天前
写了个y-mxgraph:给 draw.io 接上了 Yjs,顺便解决了部署在 iframe 里的一堆问题
前端·typescript
其实防守也摸鱼1 天前
软件安全与漏洞--软件安全编码
java·前端·网络·安全·网络安全·web·工具