【问题标题】:How to reload the component of same URL in Angular 2?如何在 Angular 2 中重新加载相同 URL 的组件?
【发布时间】:2017-01-16 16:33:10
【问题描述】:

我正在尝试使用 router.navigate 在 Angular 2 中重新加载相同的 url,但它不起作用。 网址:http://localhost:3000/landing 场景:我在http://localhost:3000/landing,现在我正在更改页面中应该重新加载页面的特定参数。

代码:

let link = ['Landing'];
this.router.navigate(link);

【问题讨论】:

  • 会发生什么?你现在有什么错误吗?

标签: angular typescript frontend angular2-routing angular2-services


【解决方案1】:

导航到某个虚拟组件,然后导航到要重新加载的组件。 //第二个参数 _skipLocationChange=true 以避免返回按钮中的 url

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

【讨论】:

  • 非常感谢!这真的很有帮助。
  • @Anish 您也可以将其标记为答案,因为它解决了您的问题。
  • @PriteshAcharya 你有别的办法吗,对我来说没用。
  • @trungk18 我发现你需要传入一个对象,this.router.navigateByUrl('/Dummy', { skipLocationChange: true }) 为我工作。
  • 我将第二次导航设置为超时。 setTimeout(() => { this.router.navigate(['/Landing']); }, 100);
【解决方案2】:

我设法通过在构造函数中使用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 方法。

【讨论】:

    【解决方案3】:
    this.router.navigateByUrl('/DummyComponent', {skipLocationChange: true}).then(()=>
    this.router.navigate(["Landing"]));
    

    【讨论】:

    • 为什么要复制现有答案?
    • @MaciejJureczko:对我来说看起来不像是同一个答案。
    • @MartijnPieters - 它并不完全相同,但它是最高得分答案的几乎相同的副本。
    • @MaciejJureczko 所以它不是副本。
    • @MartinPieters - 我不明白你为什么要把它带到词汇层面,但是好吧......所以......我不能同意。在我们可以想象的大多数含义和上下文中,副本通常并不相同。你可以有一个坏副本好副本。执行副本通常会考虑错误和缺陷。这是一个稍作修改的副本。最后,我认为这根本不重要。重要的是意图。 Headbozo 要么忽略所有以前的内容并写下他的答案,要么他复制最佳答案并修改它。 IMO 都将其作为移除的候选对象。
    猜你喜欢
    • 2018-02-05
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多