sending state with router gets undefined

时光怂恿深爱的人放手 提交于 2021-02-10 05:15:05

问题


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;

but I get this error:

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' },
  },
];

回答1:


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>

so this will fixed

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




回答2:


From what I know, when adding state to navigation, Angular is appending your values to window's History object. You can retrieve this value like this:

const { isFirst } = window.history.state;

You can read more here Keep data in the state object during navigation in Angular




回答3:


from Netanel basal:Passing Data between Routes

In a component you subscribe to activatedRoute.paramMap

 this.activatedRoute.paramMap
   .pipe(map(() => window.history.state))
   .subscribe(res=>{
       console.log(res)
   })

If you are checking in your main.app you can use router.events

this.router.events.pipe(
  filter(e => e instanceof NavigationStart),
  map(() => this.router.getCurrentNavigation().extras.state)
).subscribe(res=>{
       console.log(res)
})

And yes, always has an added variable navigationId



来源:https://stackoverflow.com/questions/63488033/sending-state-with-router-gets-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!