路由器发送状态未定义 [英] sending state with router gets undefined

查看:74
本文介绍了路由器发送状态未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,该组件使用路由器导航到具有这样的布尔变量的另一个组件

I have a component that uses router to navigate to another component with a boolean variable like this

this.router.navigate(['/consume/course/' + this.id, {state: { isFirst }} ], { replaceUrl: true });

在其他组件中,我试图像这样从路由器获取此变量

in the other component I am trying to get this variable from the router like this

 const isFirst = this.router.getCurrentNavigation().extras.state.isFirst;

但我收到此错误:

无法读取null的属性"extras"

Cannot read property 'extras' of null

为什么我的当前导航栏为空?

Why do I have null for the current navigation?

这也是我第二个组件的路由模块

Also, this is my routing module for the 2nd component

const routes: Routes = [
  {
    path: 'course/:id',
    component: CourseComponent,
    canActivate: [RedirectGuard],
    data: { menuType: 'test' },
  },
];

推荐答案

路由器导航方法带有两个参数,第一个是commands数组,另一个是

the router navigate method take two arguments the first is the commands array and the other is

navigate(
     commands: any[], 
     extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>

所以这将解决

this.router.navigate(['/consume/course/' + this.id], { 
{state: { isFirst }},
replaceUrl: true }
);

两个预览答案在获取值上都是正确的,但是您的问题与导航方法有关

both previews answer are correct about getting the value but your problem was related to navigate method

这篇关于路由器发送状态未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆