【Angular】路由router

本文介绍了Angular中如何配置路由模块,包括新建路由模块、引入组件、定义路由、预加载路由以及添加路由出口和链接。特别讨论了传参路由的实现,包括链接方式、路由定义以及如何在组件中获取路由参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 新建路由模块

ng generate module app-routing --flat --module=app

--flat                     生成在src/app

--module=app      配置到app模块

2. 引入所需组件

import { HeroesComponent } from './heroes/heroes.component';
import { DashboardComponent } from './dashboard/dashboard.component';

import { HeroDetailComponent }  from './hero-detail/hero-detail.component';

//需要使用 RouterModule 中的 Routes 类来配置路由器

import { RouterModule, Routes } from '@angular/router';

3. 定义路由

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },       //默认空路由
  { path: 'heroes', component: HeroesComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent }     //传参路由

];

4. 路由预加载

@NgModule({
  //初始化路由器
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]

})

5. 添加路由出口及链接

<nav>
    <a routerLink="/dashboard">Dashboard</a>
    <a routerLink="/heroes">Heroes</a>
</nav>

<router-outlet></router-outlet>

传参路由的不同点:

1. 链接

<a routerLink="/detail/{{hero.id}}">

2. 路由定义

{ path: 'detail/:id', component: HeroDetailComponent }     //传参路由

3. 获取路由参数

a. 导入ActivatedRoute

//保存 HeroDetailComponent 实例的路由信息
import { ActivatedRoute } from '@angular/router';
//返回上个视图

import { Location } from '@angular/common';

b. 创建私有实例

constructor(
      private route: ActivatedRoute,
      private heroService: HeroService,
      private location: Location

  ) { }

c. 调用实例的方法

  ngOnInit() {
    this.getHero();
  }
  getHero(): void {

      const id = +this.route.snapshot.paramMap.get('id');

      //route.snapshot 是一个路由信息的静态快照
      //paramMap 是一个从 URL 中提取的路由参数值的字典
      //JS 的 (+) 操作符会把字符串转换成数字

      this.heroService.getHero(id)
        .subscribe(hero => this.hero = hero);
    }
    goBack(): void {
      this.location.back();
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值