You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:如何根据条件控制RouteReuseStrategy的路由复用行为?

Angular:如何根据条件控制RouteReuseStrategy的路由复用行为?

我现在正尝试根据特定条件阻止RouteReuseStrategy的路由复用行为,但一直没成功。我有个名为comp-a的路由,它有两种触发方式:一种是通过返回按钮跳转,另一种是通过页面头部的按钮跳转。

场景说明

  • 场景1:用户在组件A中完成操作后跳转到组件B,之后点击返回按钮回到组件A,此时组件A的原有数据需要保留。这个场景我已经通过RouteReuseStrategy完美实现了。
  • 场景2:用户在组件A中完成操作后跳转到组件B,之后点击头部的按钮回到组件A,此时组件A需要从头加载,也就是ngOnInit()方法必须被调用。

目前场景2的逻辑完全不生效,这正是我遇到的问题。

我尝试过在路由中传递数据,然后在shouldDetach()函数里通过ActivatedRouteSnapshot读取,但这种方法没起到作用。

现有代码示例

app-routing.module.ts

const route: Routes = [
  { path: 'comp-a', component: CompAComponent, data: { test: true } }
];

app.component.ts(头部按钮点击事件)

// Click event on "Goto Comp A from Comp B" button
navigate() {
  this.router.navigate(['../comp-a'], { state: { data: { test: false } } });
}

custom-reuse-strategy.ts

shouldDetach(route: ActivatedRouteSnapshot) {
  return route.routeConfig?.path === 'comp-a' && (route.data as any)?.test; // 这里我尝试读取了"test"变量
}

我已经在示例项目中复现了这个问题:按钮Goto Comp A from Comp B对应场景2,按钮Go to Comp B对应场景1。

想请教下,我应该如何修改路由复用的代码,或者有没有其他可行的方法来实现这个需求?

备注:内容来源于stack exchange,提问作者avishekdr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 18:28:14