首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角getCurrentNavigation().extras

角getCurrentNavigation().extras
EN

Stack Overflow用户
提问于 2021-05-27 04:55:32
回答 3查看 4.9K关注 0票数 1

我从我的组件发送数据和路由,我想在另一个组件的构造函数中检索它:

发送数据:

代码语言:javascript
复制
this.router.navigate(['/coaches/list'], {
          state: { updateMessage: this.processMessage },
          replaceUrl: true
        });

在构造函数中检索数据:

代码语言:javascript
复制
if (this.router.getCurrentNavigation().extras?.state != null) {
  this.successMessage = this.router.getCurrentNavigation().extras.state;
}

我遇到的问题是extras.state第一次在没有任何数据的情况下是未定义的。只有当我关闭另一个组件中的对话框按钮时,这个变量才会被填充。

请告诉我如何解决这个问题,因为我正在获得错误TypeError:无法在初始加载中读取空的属性“附加”。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-05-27 04:57:20

如果getCurrentNavigation为null,我可以通过检查来解决这个问题:

代码语言:javascript
复制
    constructor(
    private fb: FormBuilder,
    private modalService: NgbModal,
    private route: ActivatedRoute,
    private router: Router,
    public commonService: CommonService
  ) {
    if (this.router.getCurrentNavigation() != null) {
      this.successMessage = this.router.getCurrentNavigation().extras.state;
    }
  }
票数 0
EN

Stack Overflow用户

发布于 2021-05-27 05:13:36

您可以通过以下方式访问状态:

代码语言:javascript
复制
history.state.updateMessage
票数 2
EN

Stack Overflow用户

发布于 2022-07-14 13:30:11

您可以将其简化为一行代码,这将使您的消息等同于null,如果getCurrentNavigation()不真实的话:

代码语言:javascript
复制
this.successMessage = this.router.getCurrentNavigation()?.extras.state;

如果要指定空值,则为:

代码语言:javascript
复制
this.successMessage = this.router.getCurrentNavigation()?.extras.state ?? 'YOUR VALUE';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67715879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档