在 Angular 中使用 navigateByUrl 转发状态

Forward state with navigateByUrl in Angular

我想传递一些数据,当使用 navigateByUrl 更改视图时

this.router.navigateByUrl(url, {state: {hello: "world"}});

在下一个视图中,我想简单地记录 hello 属性,例如

constructor(public router: Router) { }

  ngOnInit(): void {
    console.log(this.router.getCurrentNavigation().extras.state.hello)
  }

当我现在这样做时,出现错误:

ERROR TypeError: Cannot read property 'extras' of null
    at ProfileContactViewComponent.ngOnInit

我这样做是否正确,或者是否有更好的方法在视图之间传递数据? 感谢您的帮助。

这样试试

发送:

this.router.navigate([url], { state: { hello: 'world' } });

收到:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.hello); // should log out 'hello'
}

为了更好地理解,请阅读文档。 PFB link 到文档 https://angular.io/api/router/NavigationExtras#state

如果要访问 ngOninit 内部,请使用 angular 8+

提供的位置 getState 函数
import { Location } from '@angular/common';
 
export class AComponent
{
  
 
  constructor(private location:Location){
  }
 
  ngOnInit() {
    console.log(this.location.getState());
  }
}

参考 Link : https://www.tektutorialshub.com/angular/angular-pass-data-to-route/