Angular 带有可选路由的 RoutereuseStrategy

Angular RouterReuseStrategy with optional route

我只有两个可选参数的路由。默认情况下,当我尝试从这条路线中的一条导航到另一条路线时,什么也没有发生。那很好。我知道 routeParams.data.subscribe(...) 功能,但这种方法不适合我,我需要完全重新初始化组件。这就是为什么在我的演示中我使用带有标志 data {reuse: true} 的自定义 RouteReuseStrategy。我借用了 RouteReuseStrategy from here.

演示中的预期行为:转到 "Home" 选项卡,进行一些 +1,点击 "Go to same route" 按钮(这导航到相同的 HomeViewComponent),HomeViewComponent 必须重新初始化并且 Counter 必须为 0。

但是没有重新创建组件,计数器是一样的。 Stackblitz demo。谢谢!

Since Angular 5.1 你可以在定义路由时使用 onSameUrlNavigation 选项:

RouterModule.forRoot([
  { path: 'login', component: LoginViewComponent },
  { path: ':one/:two', component: HomeViewComponent, data: {reuse: false} },
  { path: '**', redirectTo: 'login' }
], { onSameUrlNavigation: 'reload' })

同时更改您的 CustomRouteReuseStrategy::shouldReuseRoute 方法如下:

public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.data.reuse !== undefined ? 
           future.data.reuse : 
           future.routeConfig === curr.routeConfig;
}

Forked Stackblitz Example