簡體   English   中英

導航到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上,並且我設置了規則設置,以在出現404錯誤(即發生頁面刷新)時返回index.html,並且我遵循了此指南,以在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並將其設置為always:

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();
    }
  }
}

到這里,您便擁有了重裝能力。 希望這可以幫助。 不幸的是,文檔在這些方面不是很清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM