角形路由器导航然后重新加载

Oma*_*ady 3 routing angular2-routing angular angular5 angular6

所以我想导航到特定路线后重新加载应用程序。

我使用router.navigate根据用户角色导航到某些路由,效果很好,但是如果来自登录页面(并非每次用户打开该特定路由),我必须在路由后重新加载页面-此处重新加载是为了更新页面语言取决于用户的语言

所以我想做的是

  else if(this.sp.role === 'Admin') {
      console.log('ooo')
      this.router.navigate(['/admin/dashboard']); 
      this.window.location.reload();
Run Code Online (Sandbox Code Playgroud)

但这会重新加载登录页面

Vla*_*lad 10

简单

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

  • 如果速度太慢,请进行真正的重新加载:`window.location.href = window.location.protocol + '//' + window.location.host + '/path/to';`。这更符合用户的期望。 (7认同)
  • 我找了很久的答案,简单又有效 (3认同)
  • 重新载入页面需要太多时间 (2认同)
  • 问题:您可以看到导航页面闪烁,然后重新加载。不太好。 (2认同)

小智 7

简单地做

location.href = '/admin/dashboard';
Run Code Online (Sandbox Code Playgroud)


Mar*_*gen 7

我把它放在我的 helperService 中:

reloadCurrentRoute() {
    let currentUrl = this.router.url;
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([currentUrl]);
    });
  }
Run Code Online (Sandbox Code Playgroud)

然后在包含导航逻辑的文件中:


_this.router.navigate(['somecomponent/anothercomponent']).then(() => {
    _this.helperService.reloadCurrentRoute();
});
Run Code Online (Sandbox Code Playgroud)

它所做的只是存储当前 url,然后导航到应用程序根目录并返回到当前 url,强制重新加载。

请注意,在您的情况下 _this 可能就是 this,具体取决于它在箭头函数中的嵌套位置和方式。Window.location.reload() 对我不起作用,它最终成为未经授权的路由,迫使我返回应用程序根路由。


dan*_*ser 5

您可以做的是将重载逻辑转移到需要重载的实际组件上。您可以订阅NavigationEnd事件,然后检查您来自的路线,例如

this.router.events
  .pipe(
    filter(value => value instanceof NavigationEnd),
  )
  .subscribe(event => {
  if (event.url === 'http://mypreviousUrl.com') {
    this.window.location.reload();
  }
});
Run Code Online (Sandbox Code Playgroud)