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

相关推荐
之歆2 分钟前
Day01_ES6+ 专业指南:从基础到实战的现代JavaScript开发(下)
前端·javascript·es6
飞翔中文网14 分钟前
Java学习笔记之抽象类与接口(设计思想)
java·笔记·学习
lichenyang45328 分钟前
鸿蒙 MVVM 实战:从 Demo 到工程化,聊聊登录、状态管理与埋点系统设计
前端
IT_陈寒44 分钟前
Vite打包时遇到的坑,原来问题出在这里
前端·人工智能·后端
kyriewen1 小时前
AI生成代码快如闪电,但我修了三个小时——它到底帮了谁?
前端·javascript·ai编程
智者知已应修善业1 小时前
【proteus设计文氏正弦波信号发生器】2023-5-9
驱动开发·经验分享·笔记·硬件架构·proteus·硬件工程
ayqy贾杰2 小时前
基层管理的三板斧,在AI时代行不通了
前端·后端·团队管理
Apifox2 小时前
Apifox 5 月更新|Postman 导入优化、Runner 支持非 root 运行、请求代码自动带鉴权
前端·后端·安全
miaowmiaow2 小时前
PSD2Code 近期更新与深度解析:从设计稿到生产级代码的完整技术栈
前端·人工智能·ai编程
Hilaku2 小时前
多标签页并发请求导致 Token 刷新失败?只有 15行代码就能解决 !
前端·javascript·程序员