[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 页面

相关推荐
乘风gg37 分钟前
还在养虾吗?虾王已诞生:微信龙虾 ClawBot
前端·ai编程·claude
小小小小宇1 小时前
LLM 长期记忆构建
前端
lichenyang4531 小时前
从 Express 老项目到 NestJS + Docker:一次车辆管理系统的渐进式重构
前端
Momo__2 小时前
VueUse createReusableTemplate —— 单文件组件内的模板复用神器
前端·vue.js
程序员小富2 小时前
我开源了一个开发者专属的智能 JSON 工具,得到了媳妇高度认可
前端·vue.js·后端
小小小小宇2 小时前
程序员如何给 LLM 装工具以及看懂推理过程
前端
写代码的皮筏艇2 小时前
React中的forwardRef
前端·react.js·面试
槑有老呆3 小时前
花三个月工资请了个 AI 程序员,结果它连青岛啤酒股价都查不了
前端
风骏时光牛马3 小时前
Verilog开发常见问题汇总解析
前端
子兮曰3 小时前
AI Coding Method Map:一张图看懂 AI 编程的完整链路
前端·人工智能·后端