【问题标题】:Angular pass route data from inside component来自组件内部的角度传递路线数据
【发布时间】:2021-10-15 19:33:13
【问题描述】:

我想要做的是将数据从组件内部传递给路由..

在应用程序组件中我有这个

this.router.events.subscribe(event => {
  if (event instanceof RoutesRecognized) {
    let current_route = event.state.root.firstChild;
    const title = current_route?.data.title;
    this.titleService.setTitle(title);
  }
});

然后像这样路由

  { path: 'confirm-registration/:code', component: HomeComponent,canActivate:[HomeGuard],data:{title:'title.landing_page'} },
  { path: 'u/:user', component: ProfileComponent},

在配置文件组件中,我需要以某种方式将标题传递给路由..

我尝试将其放入 ngOnInit 中,但它不起作用

this.router.navigate([decodeURI(this.router.url)],{state: {title: "Test Title"}});

所以我想问一下是否有可能以某种方式实现这一目标。

编辑

我试过了

let currentRoutes = this.router.config;
currentRoutes[1].data = {title: res.data.name};
this.router.resetConfig(currentRoutes);
this.router.navigate([this.router.url]);

它成功更改数据但有问题所以它只是保持无限导航

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这不应该在 ngOnInit() 中,它是一个生命周期钩子。

    如果您是在按钮点击上进行路由,那么最好编写一个函数以在点击事件上运行,并且在该函数内部,应该粘贴此行。

    【讨论】:

    • 不,我想在每次用户访问 ProfileComponent 时执行此操作(即使他第一次加载站点 - 没有 routerlink)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2020-09-12
    • 2018-05-08
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多