[Angular] 笔记 19:路由参数

2023-12-30 05:03:15

油管视频 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

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 知道子路由的存在:

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:

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:

<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:

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

在这里插入图片描述

文章来源:https://blog.csdn.net/ftell/article/details/135299154
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。