【问题标题】:Navigating to the current route in Angular 2?导航到 Angular 2 中的当前路线?
【发布时间】:2019-03-01 15:23:25
【问题描述】:

我正在尝试在 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

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

谢谢!

【问题讨论】:

标签: javascript angular typescript angular2-routing


【解决方案1】:

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

你去吧,你现在有重新加载的能力。希望这可以帮助。不幸的是,文档对这些不是很清楚。

【讨论】:

  • 有趣的答案。顺便说一句,我刚刚删除了“Snippet”降价,因为 Angular 在 Stack Overflow 中不能作为 sn-p 执行。要创建可执行示例,您可以考虑将代码复制到 Stackblitz
猜你喜欢
  • 2020-08-16
  • 2017-07-21
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多