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

相关推荐
程序员爱钓鱼3 小时前
Node.js 编程实战:图像与文件上传下载
前端·后端·node.js
kong79069284 小时前
环境搭建-运行前端工程(vue)
前端·前端环境
谷歌开发者4 小时前
Web 开发指向标|开发者工具 AI 辅助功能的 5 大实践应用
前端·人工智能
xian_wwq9 小时前
【学习笔记】数据血缘
笔记·学习·数据血缘
快乐肚皮9 小时前
一文了解XSS攻击:分类、原理与全方位防御方案
java·前端·xss
保护我方头发丶9 小时前
ESP-wifi-蓝牙
前端·javascript·数据库
日更嵌入式的打工仔9 小时前
实用:嵌入式执行时间测量常用方法
笔记·单片机
map_vis_3d10 小时前
JSAPIThree LODModel 性能优化学习笔记:细节层次模型加载
笔记·学习·3d
想学后端的前端工程师10 小时前
【Flutter跨平台开发实战指南:从零到上线-web技术栈】
前端·flutter
老王Bingo10 小时前
Qwen Code + Chrome DevTools MCP,让爬虫、数据采集、自动化测试效率提升 100 倍
前端·爬虫·chrome devtools