【问题标题】:Want to click on same route to refresh the page but not triggering anything想要点击相同的路由刷新页面但不触发任何东西
【发布时间】:2021-10-20 06:59:17
【问题描述】:

我正在开发一个带有导航菜单的 Angular v12 应用程序,该菜单具有到每个组件的工作路线。我有 1 个页面,我需要能够单击菜单并刷新页面。如果我在用户页面上并且已经单击了用户导航菜单,我想再次单击它并路由回自身以使用默认数据刷新页面。现在,当我单击导航菜单时,什么也没有发生。我在我的 NAV 组件中放置了断点,如果我再次单击该路线,它不会中断。

非常感谢任何帮助/指导。

我的路由是在 app-routing.module.ts 中配置的

const appRoutes: Routes = [
  {path: "", component: HomeComponent},
  {path: "users", loadChildren: ()=> UsersModule},
]

在我的导航组件 ts 文件中,我查看了路由器状态,但是

export class MyNavComponent implements OnInit {

  @Input() menuItems: any[] = [];
 
  selectedMenu = {} as RouteInfo;

  constructor(private router: Router) { 
 
    router.events.subscribe((event) => {

      if(event instanceof NavigationStart) {

// I placed a breakpoint here and it does not break if same menu link is clicked on again.
      
      }
    });

  }

  ngOnInit(): void {
  }
  
}

【问题讨论】:

  • 为什么要在使用 Angular 时刷新页面?

标签: angular angular-routing


【解决方案1】:

听起来您可能需要onSameUrlNavigation 配置选项。


class CustomReuseStrategy implements RouteReuseStrategy {
  shouldReuseRoute() {
    return false;
  }
}

const ROUTES: Routes = [
  ...
];

@ngModule({
  imports: [
    RouterModule.forRoot(ROUTES, { onSameUrlNavigation: 'reload' }),
  ],
  providers: [
    {
      provide: RouteReuseStrategy,
      useClass: CustomReuseStrategy,
    },
  ],
  exports: [RouterModule],
})

请注意,这仅配置 Route 是否重新处理 URL 并触发相关的操作和事件,例如重定向、守卫和解析器。默认情况下,路由器在重新导航到相同的组件类型时会重新使用组件实例,而无需先访问不同的组件。此行为由 RouteReuseStrategy 配置。为了在相同的 url 导航上重新加载路由组件,您需要将 onSameUrlNavigation 设置为 'reload' 并提供一个 RouteReuseStrategy,它为 shouldReuseRoute 返回 false。

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2013-11-05
    • 2014-09-27
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2020-12-08
    相关资源
    最近更新 更多