简体   繁体   English

Angular 中带有 navigateByUrl 的转发状态

[英]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.

相关问题 使用Angular 7的NavigateByUrl发送数据 - to send data with NavigateByUrl of Angular 7 Angular Router:用false解析的navigationByUrl() - Angular Router: navigateByUrl() resolving with false 嘲笑 Angular navigateByUrl 仍在运行页面重新加载 - Mocked Angular navigateByUrl still running page reload Angular 路由器:从navigatebyurl 返回的promise 被忽略 - Angular router: promise returned from navigatebyurl is ignored Angular 的 .navigateByUrl() 导航到页面,但没有呈现 html - Angular's .navigateByUrl() navigates to the page but html is not rendered 使用 angular 中的 this.router.navigateByUrl 传递参数 Object - Pass parameters Object with this.router.navigateByUrl in angular 页面闲置后,Angular navigationByUrl具有巨大延迟 - Angular navigateByUrl with huge delay after page is idle Angular 6 Material - 无法读取未定义的属性“navigateByUrl” - Angular 6 Material - Cannot read property 'navigateByUrl' of undefined 如何强制 navigateByUrl() 在 Angular 9 中导航域根目录? - How to force navigateByUrl() to navigate the domain root in Angular 9? 角度路由错误 - this.router.navigateByUrl() 和 this.router.navigate() - Angular routing bug - this.router.navigateByUrl() and this.router.navigate()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM