sending state with router gets undefined

Viewed 2199

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

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

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: 1 },
    replaceUrl: true
});

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

Related