I am using angular 7
Angular CLI: 7.3.9 Node: 10.16.3 OS: linux x64 Angular: 7.2.15
I use this code to pass data when route to another component
this.router.navigate(['/product'],{state: {token: data.token}});
and try to get token using following code
ngOnInit() {
console.log("#25");
this.state = this.activatedRoute.paramMap
.pipe(map(() => window.history.state));
console.log("#28"); //method 1
console.log(this.state.token);
this.router.events.pipe(filter(e => e instanceof NavigationStart))
.subscribe((e: NavigationStart) => {
this.state = this.router.getCurrentNavigation().extras.state;
console.log("#33"); //method 2
console.log(this.state.token);
});
}
the console show
undefined
both method cannot get data back, how can I do it right?
The activatedRoute.paramMap is an Observable. If you want to get its data use this.activatedRoute.snapshot.paramMap But for states this should work:
ngOnInit(){
this.state = history.state;
...
}