如何在Angular 2中重新加载具有相同URL的组件?

8
我将尝试使用router.navigate在Angular 2中重新加载相同的URL,但它无法工作。 URL: http://localhost:3000/landing 场景:我正在http://localhost:3000/landing上,并且现在我正在更改页面中的特定参数,这应该重新加载页面。
代码:
let link = ['Landing'];
this.router.navigate(link);

现在发生了什么?你有收到任何错误吗? - Reinard
3个回答

15

转到一个虚拟组件,然后导航到您想要重新加载的组件。第二个参数_skipLocationChange=true用于避免在返回按钮中出现该URL。

this.router.navigateByUrl('/DummyComponent', true);
this.router.navigate(["Landing"]);

1
非常感谢!那真的帮了我很多。 - Anish
1
@Anish,你也可以将其标记为答案,因为它解决了你的问题。 - Pritesh Acharya
@PriteshAcharya 你有另外一种处理它的方法吗?对我来说这个没有起作用。 - trungk18
4
我发现您需要传入一个对象,this.router.navigateByUrl('/Dummy', { skipLocationChange: true }) 对我有用。 - Jack Rothrock
我将第二个导航放在了一个超时函数中。setTimeout(() => { this.router.navigate(['/Landing']); }, 100); - Sydwell

7
this.router.navigateByUrl('/DummyComponent', {skipLocationChange: true}).then(()=>
this.router.navigate(["Landing"]));

2
为什么要复制现有的答案? - Maciej Jureczko
2
@MaciejJureczko:在我看来,这似乎不是同样的答案。 - Martijn Pieters
1
@MaciejJureczko 所以这不是一份复制。 - Martijn Pieters
Maciej 是正确的,虽然这是在2017年1月13日回答评论时给出的相同答案,在此帖子发布之前已经过去了整整7个月。 - Wanjia
这确实是帮助我的答案。我忘记使用 then - Jeff Huijsmans
显示剩余3条评论

0

我成功地通过在构造函数中使用PlatformLocation:onPopStateNgZone:run来实现重新加载组件。虽然这是一个变通方法,但至少它按照要求的方式工作了。

constructor(
    private route: ActivatedRoute,
    public router: Router,
    private platformLocation: PlatformLocation,
    private ngZone: NgZone) {

    platformLocation.onPopState(() => {
        if(platformLocation.pathname.startsWith("/currentRoute")) {
            this.ngZone.run(() => {
                console.log("Reloading component");
            });
        }
    });
}

onPopState 被用于在浏览器的后退/前进按钮上触发重新加载。同时,必须使用 pathname 检查,因为当组件被注入时,在任何路由中进行后退/前进操作都会调用 onPopState 方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接