我使用的是带有hashlocation策略的angular 2。

组件是用这个路由加载的:

"departments/:id/employees"

到目前为止还好。

在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:

this.router.navigate([`departments/${this.id}/employees`]);

但是什么都没有发生,为什么?


当前回答

另一种选择是使用纯js,但页面实际上会刷新。

window.location.reload(true)

其他回答

如果你的navigate()没有改变浏览器地址栏上已经显示的URL,路由器就不需要做什么。刷新数据不是路由器的工作。如果希望刷新数据,可以创建一个注入到组件中的服务,并调用该服务上的加载函数。如果将检索新数据,它将通过绑定更新视图。

另一种选择是使用纯js,但页面实际上会刷新。

window.location.reload(true)

在控制器中创建一个重定向到预期路由的函数,如下所示

redirectTo(uri:string){
   this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
   this.router.navigate([uri]));
}

然后像这样使用它

this.redirectTo('//place your uri here');

该功能将重定向到一个虚拟路由,并在用户没有意识到的情况下快速返回到目标路由。

这就是我在Angular 12中所做的。我不确定这是否适用于9以下的版本。

当您需要重新加载时,您将需要调用它。

 this.router.navigate([], {
    skipLocationChange: true,
    queryParamsHandling: 'merge' //== if you need to keep queryParams
  })

Router forRoot需要将SameUrlNavigation设置为“reload”

 RouterModule.forRoot(appRoutes, {
  // ..
  onSameUrlNavigation: 'reload',
  // ..
})

你的每个路径都需要将runGuardsAndResolvers设置为always

{
    path: '',
    data: {},
    runGuardsAndResolvers: 'always'
},

在route.navigate()的方法中实现OnInit并调用ngOnInit()

请看一个例子:

export class Component implements OnInit {

  constructor() {   }

  refresh() {
    this.router.navigate(['same-route-here']);
    this.ngOnInit();   }

  ngOnInit () {

  }