我使用的是带有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`]);
但是什么都没有发生,为什么?
当前回答
解决方案:
订阅URL参数并在那里初始化组件。没有技巧,只是“新URL ->新数据”,包括第一次加载。
对于URL参数(如/persons/:id):
constructor(protected activeRoute: ActivatedRoute, ...) {
this.activeRoute.paramMap.subscribe(paramMap => {
const id = paramMap.get('id'); // get param from dictonary
this.load(id); // load your data
});
}
对于URL查询参数(比如?q=…&returnUrl=…)(通常不是必需的):
this.activeRoute.queryParamMap.subscribe(queryParamMap => {
const returnUrl = queryParamMap.get('returnUrl');
...
});
问题的原因是:
当URL发生变化时,Angular会尽可能重用旧的组件,以节省计算机资源。加载数据是你的自定义代码,所以Angular不能为你做这件事。
其他回答
如果你通过Router Link改变路由,请遵循以下步骤:
constructor(public routerNavigate: Router){
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this.router.navigated = false;
}
})
}
我在Angular 11项目中使用这个:
reloadCurrentRoute() {
const currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS:测试和工作在所有版本以上7。
Angular 2-4路由重载破解
对我来说,在根组件(组件,存在于任何路由)中使用这个方法是有效的:
onRefresh() {
this.router.routeReuseStrategy.shouldReuseRoute = function(){return false;};
let currentUrl = this.router.url + '?';
this.router.navigateByUrl(currentUrl)
.then(() => {
this.router.navigated = false;
this.router.navigate([this.router.url]);
});
}
小技巧: 使用相同的路径和一些虚拟参数。例如,
refresh(){
this.router.navigate(["/same/route/path?refresh=1"]);
}
我使用setTimeout和navigationByUrl来解决这个问题…这对我来说很有效。
它被重定向到其他URL,而不是再次出现在当前URL…
setTimeout(() => {
this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
this.router.navigate([route]));
}, 500)