【问题标题】:Better way to resolve Angular route within the same component在同一组件中解析 A​​ngular 路由的更好方法
【发布时间】:2020-03-14 18:32:54
【问题描述】:

基本上,我的意图是使用路由参数在同一 Angular (v 9.1) 组件中调用一个函数,用于像 host/:route 这样的路由。

我在app-routing.module.ts有以下路线:

const routes: Routes = [
  { path: ':route', component: AppComponent }
];

同样的 url 导航也有 reload 行为:

@NgModule({
  imports: [RouterModule.forRoot(routes,
    {
      onSameUrlNavigation: 'reload'
    })],
  exports: [RouterModule]
})

这就是我在ngOnInit 中订阅路由事件的方式:

    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        let route = this.route;
        while (route.firstChild) {
          route = route.firstChild;
        }
        if (!this.routeMappginInitialized) {
          route.params.subscribe(param => {
            if (param.route !== undefined) {
              this.mapRouteToNavigation(param.route);
            }
          });
          this.routeMappginInitialized = true;
        }
      }
    });

这确实有效,但我想知道它是否是最佳解决方案,而我使用的大多数 Web 框架都可以轻松访问/映射路由参数。

我也试过了:

this.route.snapshot.paramMap.get('route');

但它总是返回 undefined

【问题讨论】:

    标签: angular typescript angular2-routing


    【解决方案1】:

    AppComponent 是自举组件,因此您不应该尝试使用路由加载它。修复这个设计问题,它应该可以工作,你的代码没有其他问题。

    【讨论】:

    • 通常您可能希望为特定视图做专用组件。然而,在这个小例子中,我将所有内容都放在一个页面上,在 AppComponent 内,虽然您可以滚动到特定部分,但您也应该能够使用导航到它。是的,我知道有 anchor 链接可用于此行为,但我想要更好的用户体验。
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多