You need to enable JavaScript to run this app. Angular 11 路由state传值后获取参数为undefined的问题
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11 路由state传值后获取参数为undefined的问题

报错原因

1. 路由跳转参数传法错误(直接导致拿不到值的核心原因)

Angular router.navigate() 的标准签名为:

navigate(commands: any[], extras?: NavigationExtras)

第一个参数是路由路径组成的数组,第二个参数才是包含 state 在内的导航额外配置。
你当前的写法:

this.router.navigate(['edit', this.navigationExtras]);

把 navigationExtras 当成了路径的第二段,导航配置根本没有生效,接收端自然读不到 state。

2. 接收端取值逻辑错误

  • 你传递的 state 结构是 { value: 你的item数据 },但代码里直接取了整个 state 对象,没有读取内部的 value 字段
  • router.getCurrentNavigation() 仅在「刚跳转过来、未刷新页面」的场景下有返回值,若用户刷新页面、或直接输入 edit 路由地址进入,该方法会返回 null,直接访问 navigation.extras.state 会抛出空指针错误
修正代码

list.component.ts 调整

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
  constructor(private router: Router) { }

  ngOnInit(): void {}

  onGoToEdit(item: any): void {
    // 正确传参:路径数组为第一参数,导航配置为第二参数
    this.router.navigate(['edit'], { state: { value: item } });
  }

  onGoToSee(item: any): void {
    this.router.navigate(['details'], { state: { value: item } });
  }

  onGoToDelete(item: any): void {
    alert("Delete");
  }
}

edit.component.ts 调整

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss']
})
export class EditComponent implements OnInit {
  value: any = null;

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit(): void {
    // 直接读取浏览器持久化的 history state,兼容页面刷新场景
    const state = history.state as { value: any };
    this.value = state?.value;
    console.log(this.value);
  }
}
扩展建议

如果需要支持链接分享、直接输入地址打开页面的场景,不建议使用隐式 state 传参,可改用路径参数的方式:

  • 路由配置中声明:{ path: 'edit/:id', component: EditComponent }
  • 跳转时传参:this.router.navigate(['edit', item])
  • 接收时取值:this.activatedRoute.snapshot.paramMap.get('id')

内容的提问来源于stack exchange,提问作者user15242898

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.01 19:54:03