[英]Forward state with navigateByUrl in Angular
i want to pass some data, when changing the view with navigateByUrl like我想传递一些数据,当使用navigateByUrl更改视图时
this.router.navigateByUrl(url, {state: {hello: "world"}});
In the next view i want to simply log the hello attribute like在下一个视图中,我想简单地记录 hello 属性,例如
constructor(public router: Router) { }
ngOnInit(): void {
console.log(this.router.getCurrentNavigation().extras.state.hello)
}
When I now do it this way, i get an error:当我现在这样做时,我收到一个错误:
ERROR TypeError: Cannot read property 'extras' of null
at ProfileContactViewComponent.ngOnInit
Am i doing this correctly or is there a better way to pass the data between the views?我这样做正确还是有更好的方法在视图之间传递数据? Thanks for your help.谢谢你的帮助。
Try like this像这样尝试
Send :发送 :
this.router.navigate([url], { state: { hello: 'world' } });
Recieve:收到:
constructor(private router: Router) {
console.log(this.router.getCurrentNavigation().extras.state.hello); // should log out 'hello'
}
For better understanding read the documentation.为了更好地理解阅读文档。 PFB the link to documentation https://angular.io/api/router/NavigationExtras#state PFB 文档链接https://angular.io/api/router/NavigationExtras#state
If you want to access inside ngOninit, use the location getState function which is available from angular 8+如果要访问 ngOninit 内部,请使用 angular 8+ 提供的 location getState 函数
import { Location } from '@angular/common';
export class AComponent
{
constructor(private location:Location){
}
ngOnInit() {
console.log(this.location.getState());
}
}
Reference Link : https://www.tektutorialshub.com/angular/angular-pass-data-to-route/参考链接: https : //www.tektutorialshub.com/angular/angular-pass-data-to-route/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.