导航到 Angular 2 中的当前路线?

Navigating to the current route in Angular 2?

我正在尝试重新加载 Angular 中的当前页面。

所以当我重新加载页面时,我的根组件被调用并执行了这一行:

console.log(this.router.routerState.snapshot.url)

打印“/component-x”

然后我执行这行代码:

this.router.navigate(['/component-x]')

它不起作用,我退出了我的应用程序。

是否支持导航到Angular中的当前路线? 我还能如何实现重新加载当前页面?

请注意,我的应用程序托管在 AWS 上的 Cloudfront 上,并且我已将规则设置为 returns index.html 当出现 404 错误时(即发生页面刷新时),并且我有按照本指南重新加载 Angular 中的当前路线:https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

但是还是不行。有人可以指出我遗漏了什么吗?

谢谢!

您可以使用来自 Angular 路由器的 onSameUrlNavigation

@ngModule({
   imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
   exports: [RouterModule],
})

然后在您的路线上使用 runGuardsAndResolvers 并将其设置为始终:

export const routes: Routes = [
 {
   path: 'my-path',
   component: MyComponent,
   children: [
     {
       path: '',
       loadChildren: './pages/my-path/mycomponent.module#MyComponentModule',
     },
   ],
   canActivate: [AuthenticationGuard],
   runGuardsAndResolvers: 'always',
 }
]

通过这两项更改,您的路由器已配置完毕。现在你需要在你的组件中挂钩 NavigationEnd:

export class MyComponent implements OnInit, OnDestroy{
 // ... your class variables here
 navigationSubscription;
 constructor(
   // … your declarations here
   private router: Router,
  ) {
   // subscribe to the router events - storing 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.initialiseMyComponent();
     }
   });
 }

 initialiseMyComponent() {
   // Set default values and re-fetch any data you need.
 }
 ngOnDestroy() {
    // avoid memory leaks here by cleaning up after ourselves. If we  
    // don't then we will continue to run our initialiseInvites()   
    // method on every navigationEnd event.
    if (this.navigationSubscription) {  
       this.navigationSubscription.unsubscribe();
    }
  }
}

好了,你现在可以重新加载了。希望这可以帮助。不幸的是,文档对这些不是很清楚。