【问题标题】:Angular RouterReuseStrategy with optional route带有可选路由的 Angular RoutereuseStrategy
【发布时间】:2018-06-26 16:40:38
【问题描述】:

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

演示中的预期行为:转到“主页”选项卡,进行一些 +1,单击“转到同一路线”按钮(这会导航到相同的 HomeViewComponent),HomeViewComponent 必须重新初始化,并且 Counter 必须为 0。

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

【问题讨论】:

    标签: angular angular-router


    【解决方案1】:

    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

    【讨论】:

    • 太棒了,让我开心!
    猜你喜欢
    • 2013-05-07
    • 2023-03-03
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2016-10-12
    • 2010-12-07
    相关资源
    最近更新 更多