【问题标题】:how to activate a component each time the parameter in the route that activetes it changes每次激活组件的路由中的参数更改时如何激活组件
【发布时间】:2021-07-27 16:24:21
【问题描述】:

我读到如果唯一改变的是路由参数,路由器会重用组件及其模板

因此,如果被激活的组件在其 ngOnInit() 中执行逻辑,它只会在这样的路由第一次激活它时执行 http://../projects/12

当切换到路径 http/../projects/45 时,如何使该逻辑执行

就我而言,我有这个项目:https://stackblitz.com/edit/planificador?file=src/app/planificador/components/resumen/resumen.component.ts

当我选择一个新项目时,第一次只执行 ResumenComponent 的 ngOnInit() 方法

谢谢

【问题讨论】:

    标签: angular-routing angular-router


    【解决方案1】:

    TLDR

    StackBlitz app.


    说明

    对于这种情况,我们可以使用自定义RouteReuseStrategy

    app.module.ts

    export class CustomRouteReuseStrategy extends BaseRouteReuseStrategy {
      shouldReuseRoute(
        future: ActivatedRouteSnapshot,
        curr: ActivatedRouteSnapshot
      ): boolean {
        const determinantParam = "proyectoId";
    
        if (
          !curr?.routeConfig?.path.includes(determinantParam) ||
          !future?.routeConfig?.path.includes(determinantParam)
        ) {
          return super.shouldReuseRoute(future, curr);
        }
    
        return future.params[determinantParam] === curr.params[determinantParam];
      }
    }
    

    BaseRouteReuseStrategy 定义为 herehere 是为什么在使用新的 param 时它没有创建新组件的原因:

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
      return future.routeConfig === curr.routeConfig;
    }
    

    它返回true,因为来自两个对象(futurecurr)的routeConfig 的值是planificador.module.ts 中Routes 数组中定义的第一项强>:

    {
      path: '',
      component: PlanificadorAppComponent,
      children: [
        {
          path: ':empleadoId/proyectos',
          component: MainContentComponent,
        },
        {
          path: ':empleadoId/proyectos/:proyectoId',
          component: MainContentComponent,
        }
      ]
    },
    

    正如预期的那样,Angular 通过遍历路由配置并比较之前的状态来构建下一个导航。这个状态被定义为一棵树,其中每个注释都包含有意义的信息。在这些信息中,有params对象,它的键是参数(例如:proyectoId),值是由URL的样子决定的。

    那么,我们的自定义策略是如何确保如果导航涉及路径为:empleadoId/proyectos/:proyectoId 的路由,则只有在此条件为真时才应重用此路由(及其组件):

    future.params[determinantParam] === curr.params[determinantParam]
    

    此外,如果您想了解有关 Angular 路由器的更多信息,可以查看以下文章:

    【讨论】:

    • 非常感谢您提供了一个很好的解决方案和更好的解释
    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2014-07-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多