Angular 12:导航和重新加载页面

问题描述 投票:0回答:2

我有一个角度应用程序,我需要在导航后重新加载页面。我已经应用了 this 解决方案,但

window.location.reload();
不适用于生产。所以我在
useHash: true
文件中添加了
app-routing.module.ts
。但这也给我在应用程序中应用 SSR 时带来了问题。所以我需要以下代码的替代方法:

this.router.navigate(['path/to'])
  .then(() => {
    window.location.reload();
  });

我尝试过应用

window.location.href = window.location.href
window.location.href = window.location.protocol + '//' + window.location.host + '/path/to';
而不是
window.location.reload();
但它不会按预期重新加载页面。

还有其他方法可以实现在 Angular 12 中导航后重新加载吗?请大家帮忙指导一下。

编辑: 为什么要重新加载: 在应用程序中,用户登录后,通知会显示在标题中。如果页面未重新加载,则不会显示数据。

javascript angular typescript navigation reload
2个回答
1
投票

您可以尝试重定向到 root,然后重定向到您的最终目的地:

this.router.navigate(['/'])
  .then(() => {
    this.router.navigate(['path/to'])
  });

0
投票

您可以在所需组件路径的

ngOnInit()
中设置超时,并在超时内调用
window.location.reload();
window.location.href = window.location.href
,例如:

ngOnInit(): void {
   
    if (!localStorage.getItem('refresh_called')) {
      setTimeout(() => {
        console.log('calling reload');
        localStorage.setItem('refresh_called', 'true');
        window.location.reload();
      }, 1500);
    }
  }

localStorage 处理是为了避免一遍又一遍地调用超时(仅一次)。

希望这可以帮助别人。

© www.soinside.com 2019 - 2024. All rights reserved.