angular 7 route state unable to get passed data

Vin*_*hen 2 state routes angular

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);
    });

}
Run Code Online (Sandbox Code Playgroud)

the console show

25 product.component.ts:25:10

28 product.component.ts:28:10

undefined

both method cannot get data back, how can I do it right?

Sud*_*jee 7

我正在使用角 8

我路由的组件

this.router.navigate(['/ledger-card'], { queryParams: { branchId: '10', loanAcc: '2738'}});
Run Code Online (Sandbox Code Playgroud)

我接收路由数据的组件

const param = this.route.snapshot.queryParamMap;
    if  (param.get('branchId')) {
      const branchId =  param.get('branchId');
      const loanAcc = param.get('loanAcc');
    }
Run Code Online (Sandbox Code Playgroud)

** 确保您导入 ActivatedRoute

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
Run Code Online (Sandbox Code Playgroud)

为了在不使用查询参数的情况下在组件之间传递数据

您要路由的组件

this.router.navigate(['/hello'],{state: {data: '24'}});
Run Code Online (Sandbox Code Playgroud)

您接收的组件

const s = this.router.getCurrentNavigation().extras.state;
Run Code Online (Sandbox Code Playgroud)

请确保在构造函数中执行接收代码,因为它的作用域在那里结束。您将无法在 ngOnInit() 上获取数据。

工作示例:https : //stackblitz.com/edit/angular-fygew5


tan*_*ano 5

activateRoute.paramMap 是一个 Observable。如果您想获取其数据,请使用 this.activatedRoute.snapshot.paramMap 但对于州来说,这应该有效:

ngOnInit(){
   this.state = history.state;
   ...
}
Run Code Online (Sandbox Code Playgroud)