我使用的是带有hashlocation策略的angular 2。

组件是用这个路由加载的:

"departments/:id/employees"

到目前为止还好。

在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:

this.router.navigate([`departments/${this.id}/employees`]);

但是什么都没有发生,为什么?


当前回答

这现在可以在Angular 5.1中使用Router配置中的onSameUrlNavigation属性来实现。

我已经添加了一个博客来解释如何在这里,但它的要点如下

https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

在路由器配置中启用onSameUrlNavigation选项,将其设置为“reload”。当你试图导航到一个已经激活的路由时,这将导致路由器触发一个事件循环。

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

在路由定义中,将runGuardsAndResolvers设置为always。这将告诉路由器总是启动守卫和解析器循环,触发相关事件。

export const routes: Routes = [
 {
   path: 'invites',
   component: InviteComponent,
   children: [
     {
       path: '',
       loadChildren: './pages/invites/invites.module#InvitesModule',
     },
   ],
   canActivate: [AuthenticationGuard],
   runGuardsAndResolvers: 'always',
 }
]

最后,在您希望启用重新加载的每个组件中,都需要处理事件。这可以通过导入路由器、绑定事件并调用初始化方法来实现,该方法可以重置组件的状态并在需要时重新获取数据。

export class InviteComponent implements OnInit, OnDestroy {
 navigationSubscription;     

 constructor(
   // … your declarations here
   private router: Router,
 ) {
   // subscribe to the router events. Store 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.initialiseInvites();
     }
   });
 }

 initialiseInvites() {
   // Set default values and re-fetch any data you need.
 }

 ngOnDestroy() {
   if (this.navigationSubscription) {
     this.navigationSubscription.unsubscribe();
   }
 }
}

所有这些步骤就绪后,您应该启用了路由重新加载。

其他回答

这招对我很管用:

let url = `departments/${this.id}/employees`;

this.router.navigated = false;
this.router.navigateByUrl(url);

在控制器中创建一个重定向到预期路由的函数,如下所示

redirectTo(uri:string){
   this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
   this.router.navigate([uri]));
}

然后像这样使用它

this.redirectTo('//place your uri here');

该功能将重定向到一个虚拟路由,并在用户没有意识到的情况下快速返回到目标路由。

有点硬核,但是

this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {

    this.router.onSameUrlNavigation = 'ignore';

});

写一个函数。, reloadCurrentPage。由于window是一个全局对象,可以直接在Angular组件中重用,window.location.reload()会重新加载当前活动的页面。

function reloadCurrentPage() {
    window.location.reload();
}

如果你通过Router Link改变路由,请遵循以下步骤:

  constructor(public routerNavigate: Router){

         this.router.routeReuseStrategy.shouldReuseRoute = function () {
            return false;
          };

          this.router.events.subscribe((evt) => {

            if (evt instanceof NavigationEnd) {

                this.router.navigated = false;
             }
          })
      }