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

时间:2018-09-25 23:04:25

标签: javascript angular typescript angular2-routing

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

因此,当我重新加载页面时,将调用我的根组件并执行以下行:

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

显示“ / component-x”

然后执行以下代码行:

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

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

是否支持在Angular中导航到当前路线? 以及如何才能重新加载当前页面?

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

但是它仍然无法正常工作。有人可以指出我所缺少的吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用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();
    }
  }
}

然后您就可以拥有重新加载功能。希望这可以帮助。不幸的是,文档在这些方面不是很清楚。