【问题标题】:routerLink with parameters is changing the URL but not navigating or reloading the component带参数的 routerLink 正在更改 URL 但不导航或重新加载组件
【发布时间】:2018-06-08 09:09:40
【问题描述】:

我已经检查了相关问题router.navigate changes the URL, but is not rendering the component,但同样的情况导致了同样的结果。

我的路线模块中有一条路线:

        {
            path: "competition/details",
            loadChildren: "../pages/competitions/competitions-details/competitions-details.module#CompetitionsDetailsModule"
        }

那个页面(“比赛细节”)呈现了我的元素:

<standings-regular></standings-regular>

然后在组件中检查 2 个可选参数:

    this.competitionId = this.activatedRoute.snapshot.params.competition;
    this.condition = this.activatedRoute.snapshot.params.condition;

最后我使用这些参数“竞争”和“条件”来构建一个数组。到目前为止,如果我直接在浏览器中使用 URL,一切正常:

例如:http://localhost:4200/competition/details;competition=219;condition=home

现在,这基本上代表了对于给定比赛的同一张桌子的不同视图,对于一点上下文。

http://localhost:4200/competition/details;competition=219;condition=home 将为第 219 场比赛的每支球队提供只有主场比赛的积分榜。

http://localhost:4200/competition/details;competition=219 创建包含来自比赛 219 的所有比赛的表格。

所以,我想在同一个表中创建一个链接来导航到新的 URL,但是当我尝试这样做时,它只会更改浏览器中的 URL,但不会更改视图。

这是我尝试导航的方式:

        <ul class="dropdown-menu btn-primary dropdown-menu-right">
            <li>
                <a md-ripple [routerLink]="['/competition/details', {competition: '219'}]">Completa</a>
            </li>
            <li>
                <a md-ripple [routerLink]="['/competition/details', {competition: '219', condition: 'home'}]">Home Only</a>
            </li>
        </ul>

我也尝试用 (click)="" 事件替换 routerLink ,该事件触发组件中的方法进行导航,但结果相同,更改浏览器中的 URL,但不执行任何操作。

我尝试了 router.navigate() 和 router.navigateByUrl()

有什么想法吗?

【问题讨论】:

  • 有人问过类似的问题here。也许会有所帮助。
  • 试试这个:ngOnChanges(){this.ngOniInit()}。它对我有用。

标签: angular typescript angular4-router


【解决方案1】:

您应该订阅activatedRoute,而不是从“snapshot.params”获取参数值。

import { ActivatedRoute, Router, ParamMap } from "@angular/router";

将此代码放入您的ngOnInit()

this.activatedRoute.paramMap.subscribe((params: ParamMap) => {
    this.competitionId = params.get('competitionId ');
    let condition = params.get('condition ');
    //business logic what changes you want on the page with this new data.
});

通过快照,在更改 url 中的路径参数时不会发生重新加载,因为没有调用构造函数。但是使用 subscribe 它会监听参数中发生的变化。

【讨论】:

  • 完美运行!很好的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2017-06-29
  • 2013-04-19
  • 1970-01-01
  • 2020-08-16
  • 2017-02-23
相关资源
最近更新 更多