我没有发现这些对于 Angular 8 来说是一个好的和彻底的解决方案。一些建议最终创建了无限循环,导致,咳咳,堆栈溢出。其他人对我的口味来说太老套了。我在网上找到了一个很好的解决方案,但是由于我不能在这里只发布一个链接,所以我会尽力根据链接总结我所做的事情以及为什么我认为这是一个可靠的解决方案。它允许您只影响需要行为的某些路由而不影响其他路由,并且您不需要滚动任何自定义类来使其工作。
来自 Simon McClive 的解决方案
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
首先,修改你的应用路由模块配置:
@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule] })
接下来,修改您想要影响的路线。如果您不使用身份验证,则可以省略 canActivate 参数:
export const routes: Routes = [
{
path: ‘invites’,
component: InviteComponent,
children: [
{
path: ‘’,
loadChildren: ‘./pages/invites/invites.module#InvitesModule’,
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: ‘always’, //there are three options for this - see Simon's post. 'Always' is the heaviest-handed and maybe more than you need.
}
]
最后,更新你的类以监听导航事件并采取相应的行动(确保在退出时取消注册监听器):
export class AwesomeComponent implements OnInit, OnDestroy{
// ... your class variables here
navigationSubscription;
constructor( private router: Router ) {
// subscribe to the router events and store the subscription so
// we can unsubscribe later
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event, re-initalize the component
if (e instanceof NavigationEnd) {
this.myInitFn();
}
});
}
myInitFn() {
// Reset anything affected by a change in route params
// Fetch data, call services, etc.
}
ngOnDestroy() {
// avoid memory leaks here by cleaning up
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}