【问题标题】:Angular 15 Activated Route snapshot params get () returns null?Angular 15 Activated Route snapshot params get()返回null?
【发布时间】:2023-01-13 07:08:23
【问题描述】:

我是 Angular 的新手,两天后就被屏蔽了。命令 ”const pokemonId: string|null = this.route.snapshot.paramMap.get('id');" 将 null 返回给 pokemonId 但通常它会给我来自 URL (http://localhost:4200/pokemon/4) 的字符串,就像这里的 "4"

detail-pokemon.component.ts :


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { POKEMONS } from '../mock-pokemon-list';
import { Pokemon } from '../pokemon';

@Component({
  selector: 'app-detail-pokemon',

  templateUrl: './detail-pokemon.component.html',
  
})


constructor (private route: ActivatedRoute,  ){}
ngOnInit()  {

this.pokemonList = POKEMONS;

 const pokemonId: string|null = this.route.snapshot.paramMap.get('id');

 if (pokemonId) {
 
 this.pokemon = this.pokemonList.find(pokemon => pokemon.id == pokemonId)}}}

app-routing.module.ts
const routes: Routes = [
  { path: 'pokemons',component: ListPokemonComponent },
  {path : 'pokemon/:id ', component: DetailPokemonComponent},
  {path: '', redirectTo : 'pokemons', pathMatch: 'full'}
];

我尝试使用 getAll 和所有针对像我这样的情况提出的解决方案。

【问题讨论】:

    标签: angular url parameters snapshot angular-activatedroute


    【解决方案1】:

    不要使用 paramsMap 试试这个

    import {ActivatedRoute} from '@angular/router';
        
        constructor(
    
            private route: ActivatedRoute
    
          ) {}
        
        **const pokemonId: string|null=this.route.snapshot.params.id**
    

    【讨论】:

      【解决方案2】:

      您需要删除路径中:id 之后的空格。所以改变:

      'pokemon/:id '
                  _
      

      到:

      'pokemon/:id'
      

      【讨论】:

        【解决方案3】:

        感谢 HARIDHASS 的回答?

        愚蠢的错误,在 app-routing.module.ts 中的“id”之后有一个空格

        我花了两天时间。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-25
          • 2016-09-01
          • 1970-01-01
          • 2022-06-15
          • 1970-01-01
          相关资源
          最近更新 更多