我使用的是带有hashlocation策略的angular 2。
组件是用这个路由加载的:
"departments/:id/employees"
到目前为止还好。
在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:
this.router.navigate([`departments/${this.id}/employees`]);
但是什么都没有发生,为什么?
我使用的是带有hashlocation策略的angular 2。
组件是用这个路由加载的:
"departments/:id/employees"
到目前为止还好。
在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:
this.router.navigate([`departments/${this.id}/employees`]);
但是什么都没有发生,为什么?
当前回答
假设你想要刷新的组件的路由是视图,然后使用这个:
this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
return false;
}
return (future.routeConfig === curr.routeConfig);
};
你可以在方法中添加一个调试器,以了解导航到“departments/:id/employees”后的确切路径。
其他回答
我在Angular 11项目中使用这个:
reloadCurrentRoute() {
const currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS:测试和工作在所有版本以上7。
重载当前路由在angular 2非常有用的链接重载当前路由在angualr 2或4
在这里定义两种技术来做到这一点
使用虚拟查询参数 使用虚拟路由
欲了解更多信息,请参见上面的链接
一个解决方案是传递一个虚拟参数(即以秒为单位的时间),这样链接总是被重新加载:
this.router.navigate(["/url", {myRealData: RealData, dummyData: (new Date).getTime()}])
从@angular/ Router中导入Router和ActivatedRoute
import { ActivatedRoute, Router } from '@angular/router';
注入Router和ActivatedRoute(以防你需要URL中的任何东西)
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
从URL中获取所需的任何参数。
const appointmentId = this.route.snapshot.paramMap.get('appointmentIdentifier');
使用一个技巧,通过导航到一个虚拟url或主url,然后到实际url将刷新组件。
this.router.navigateByUrl('/appointments', { skipLocationChange: true }).then(() => {
this.router.navigate([`appointment/${appointmentId}`])
});
在你的情况下
const id= this.route.snapshot.paramMap.get('id');
this.router.navigateByUrl('/departments', { skipLocationChange: true }).then(() => {
this.router.navigate([`departments/${id}/employees`]);
});
如果你使用一个虚拟路由,那么你会看到一个标题闪烁'未找到',如果你已经实现了一个未找到的url,以防不匹配任何url。
这招对我很管用:
let url = `departments/${this.id}/employees`;
this.router.navigated = false;
this.router.navigateByUrl(url);