我使用的是带有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() {
return false;
// or
return true;
};
其他回答
这招对我很管用:
let url = `departments/${this.id}/employees`;
this.router.navigated = false;
this.router.navigateByUrl(url);
这现在可以在Angular 5.1中使用Router配置中的onSameUrlNavigation属性来实现。
我已经添加了一个博客来解释如何在这里,但它的要点如下
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
在路由器配置中启用onSameUrlNavigation选项,将其设置为“reload”。当你试图导航到一个已经激活的路由时,这将导致路由器触发一个事件循环。
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
})
在路由定义中,将runGuardsAndResolvers设置为always。这将告诉路由器总是启动守卫和解析器循环,触发相关事件。
export const routes: Routes = [
{
path: 'invites',
component: InviteComponent,
children: [
{
path: '',
loadChildren: './pages/invites/invites.module#InvitesModule',
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: 'always',
}
]
最后,在您希望启用重新加载的每个组件中,都需要处理事件。这可以通过导入路由器、绑定事件并调用初始化方法来实现,该方法可以重置组件的状态并在需要时重新获取数据。
export class InviteComponent implements OnInit, OnDestroy {
navigationSubscription;
constructor(
// … your declarations here
private router: Router,
) {
// subscribe to the router events. Store the subscription so we can
// unsubscribe later.
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event re-initalise the component
if (e instanceof NavigationEnd) {
this.initialiseInvites();
}
});
}
initialiseInvites() {
// Set default values and re-fetch any data you need.
}
ngOnDestroy() {
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
所有这些步骤就绪后,您应该启用了路由重新加载。
如果你的navigate()没有改变浏览器地址栏上已经显示的URL,路由器就不需要做什么。刷新数据不是路由器的工作。如果希望刷新数据,可以创建一个注入到组件中的服务,并调用该服务上的加载函数。如果将检索新数据,它将通过绑定更新视图。
解决方案:
订阅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不能为你做这件事。
这对我来说很管用
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));