我使用的是带有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.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});
其他回答
在控制器中创建一个重定向到预期路由的函数,如下所示
redirectTo(uri:string){
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([uri]));
}
然后像这样使用它
this.redirectTo('//place your uri here');
该功能将重定向到一个虚拟路由,并在用户没有意识到的情况下快速返回到目标路由。
重载当前路由在angular 2非常有用的链接重载当前路由在angualr 2或4
在这里定义两种技术来做到这一点
使用虚拟查询参数 使用虚拟路由
欲了解更多信息,请参见上面的链接
有点硬核,但是
this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});
解决方案:
订阅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不能为你做这件事。
这就是我在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'
},