[Angular] 笔记 19:路由参数

油管视频 Route Parameters

路由参数是跟在 url 后面的数字,字符串,或者 数字+字符串,例如如下 url 中的 123,此类参数会传给后端:

www.facebook.com/profile/123

首先将 pokemon-template-form 组件移到 pokeman-base 模块中,vscode 直接 drag + drop 就可以。然后从 app.module.ts 中移除与此组件相关代码。

1. 在 pokemon-base.modle.ts 中引入 routes

ts 复制代码
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PokemonListComponent } from './pokemon-list/pokemon-list.component';
import { PokemonDetailComponent } from './pokemon-detail/pokemon-detail.component';
import { PokemonService } from '../services/pokemon.service';
import { HttpClientModule } from '@angular/common/http';
import { PokemonTemplateFormComponent } from './pokemon-template-form/pokemon-template-form.component';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';

// 新增代码
const routes: Routes = [
  {
    path: '',
    children: [
      { path: '', component: PokemonListComponent },
      { path: ':id', component: PokemonTemplateFormComponent },
    ],
  },
];

@NgModule({
  declarations: [
    PokemonListComponent,
    PokemonDetailComponent,
    PokemonTemplateFormComponent, // 新增代码
  ],
  imports: [
    CommonModule,
    HttpClientModule,
    FormsModule, // 新增代码
    RouterModule.forChild(routes), // 新增代码
  ],
  exports: [PokemonListComponent, PokemonDetailComponent],
  providers: [PokemonService],
})
export class PokemonBaseModule {}

2. 使 app-routing.module.ts 中的 routes 知道子路由的存在:

ts 复制代码
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { NotfoundComponent } from './notfound/notfound.component';

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  // 新增代码
  {
    path: 'pokemon',
    loadChildren: () =>
      import('./pokemon-base/pokemon-base.module').then(
        (m) => m.PokemonBaseModule
      ),
  },
  { path: '**', component: NotfoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

3. web 页面:

4. 接下来,将路由参数传给 getPokemon() 函数

pokemon-template-form.component.ts:

ts 复制代码
import { Component, OnInit } from '@angular/core';
import { Pokemon, PokemonType } from '../../models/pokemon';
import { PokemonService } from '../../services/pokemon.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-pokemon-template-form',
  templateUrl: './pokemon-template-form.component.html',
  styleUrls: ['./pokemon-template-form.component.css'],
})
export class PokemonTemplateFormComponent implements OnInit {
  pokemon!: Pokemon;

  // create dropdown for Pokemon type
  pokemonType: PokemonType[] = [
    {
      key: 0,
      value: 'Fire',
    },
    {
      key: 1,
      value: 'Water',
    },
  ];

  constructor(
    private pokemonService: PokemonService,
    private router: Router, // 新增代码
    private route: ActivatedRoute // 新增代码
  ) {}

  toggleIsCool(object: any) {
    console.log(object);
    this.pokemon.isCool = !this.pokemon.isCool;
  }

  ngOnInit() {
    this.pokemon = {} as Pokemon; // ?? 新增代码
    // 代码修改:
    this.route.params.subscribe((data: Params) => {
      this.pokemonService.getPokemon(data['id']).subscribe((data: Pokemon) => {
        this.pokemon = data;
      });
    });
  }

  handleSubmit(object: any) {
    console.log(object);
  }

  // 新增代码
  back(): void {
    this.router.navigate(['/pokemon']);
  }
}

5. web 页面

6. 增加 back button,

以返回到 url http://localhost:4200/pokemon
pokemon-detail.component.html:

html 复制代码
<tr>
  <td class="pokemon-td" [class.cool-bool]="detail.isCool">
    {{ detail.id }} : {{ detail.name }}
    {{ detail.isCool == true ? "is COOL" : "is NOT COOL" }}
  </td> 
  <button [routerLink]="['/pokemon', detail.id]">Details</button>
  <button (click)="onRemove()">Remove Pokemon</button>
</tr>

pokemon-template-form.component.html, 在 </form> 前增加一个 button:

html 复制代码
  <button type="submit" [disabled]="!form.valid">Save</button>
  <!-- 返回button -->
  <button type="button" (click)="back()">Go Back</button>
</form>
<div>
  MODEL: {{ pokemon | json }} FORM: {{ form.value | json }} ERROR:
  <div *ngIf="!pokemonName.pristine">NOT PRINSTINE ANYMORE IT IS DIRTY!</div>
</div>

7. web 页面

相关推荐
张鑫旭4 分钟前
AI时代2025年下半年学的这些Web前端特性有没有用?
前端·ai编程
pinkQQx5 分钟前
H5唤醒APP技术方案入门级介绍
前端
Lefan8 分钟前
UniApp 隐私合规神器!一键搞定应用市场审核难题 - lf-auth 隐私合规助手
前端
Null1559 分钟前
浏览器唤起桌面端应用(进阶篇)
前端·浏览器
Jing_Rainbow11 分钟前
【Vue-2/Lesson62(2025-12-10)】模块化与 Node.js HTTP 服务器开发详解🧩
前端·vue.js·node.js
风度前端1 小时前
用了都说好的 uniapp 路由框架
前端
冴羽1 小时前
2026 年 Web 前端开发的 8 个趋势!
前端·javascript·vue.js
码银1 小时前
ruoyi的前端(vue)新增的时候给字典设置默认值 但不能正常
前端
凉、介1 小时前
深入 QEMU Guest Agent:虚拟机内外通信的隐形纽带
c语言·笔记·学习·嵌入式·虚拟化
凌览2 小时前
别再死磕 Nginx!http-proxy-middleware 低配置起飞
前端·后端