【问题标题】:Angular Router: Get route config that matched the current routeAngular Router:获取与当前路由匹配的路由配置
【发布时间】:2021-02-17 00:46:18
【问题描述】:

我的 Angular 项目中有以下路由配置:

export const routes: Routes = [
  { path: 'a/:id', loadChildren: './a/a.module#AModule', data: {a: a}},
  { path: 'b/:id',  loadChildren: './b/b.module#BModule', data: {a: b}}
];

现在我可以像这样得到我的路由配置:

this.router.config //outputs the above array

this.router.url 显示a,但我如何正确识别正确的Route,因为配置具有未解析的路径,而路由器拥有已解析的路径。

我想这样做的原因是访问app.component 中的data,其中我的router-outlet 不在组件本身中(角度文档说data 对象只能访问路由组件本身。

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    可以在没有事件的情况下访问此配置,例如从 onInit 根目录(但也可以在订阅正文中使用):

    const config = !!this.activatedRoute.snapshot.root.firstChild.children.length
          ? this.activatedRoute.snapshot.root.firstChild.firstChild.data
          : this.activatedRoute.snapshot.root.firstChild.data;
    this.hideHeader = config['hideHeader'] ?? false;
    

    子长度检查是针对两级配置的:

      RouterModule.forRoot([
        {
          path: 'login',
          component: WelcomePageComponent,
          data: {
            hideHeader: true,
          },
        },
        {
          path: '',
          canActivateChild: [AuthGuard, ACLGuard],
          children: [
            {
              path: '',
              redirectTo: 'wizard',
              pathMatch: 'full',
            },
            {
              path: 'wizard',
              data: {
                hideHeader: true,
              },
            },
          ],
        },
      ],
    

    【讨论】:

      【解决方案2】:

      您可以在应用组件中使用路由器插座的激活输出

      <router-outlet (activate)="onActivate($event)"></router-outlet>
      

      它给你laoded组件

      在您的 app.component.ts 中

      onActivate(event : any) {
         console.log(event);
      }
      

      示例:

      【讨论】:

      • 我只想访问data 而不是整个组件。我不需要访问该组件。
      【解决方案3】:

      我会解决这个问题,拆分延迟加载路线,使其更简单。 根路由:

      export const routes: Routes = [
        { path: 'a', loadChildren: './a/a.module#AModule'},
        { path: 'b',  loadChildren: './b/b.module#BModule'}
      ];
      

      模块 A 路由:

      export const aModuleRoutes: Routes = [
                   { path: 'item/:id', component: YourComponent, data: {a: a}}  
      ]; 
      

      模块 B 路由:

      export const bModuleRoutes: Routes = [
                   { path: 'item/:id', component: YourComponent, data: {a: b}}  
      ];
      

      在这里,每个模块都有单独的路线,您可以使用单独的模块路线。 快乐编码

      【讨论】:

      • 我不确定这将如何帮助我访问data?此外,我想保持延迟加载。
      【解决方案4】:

      我用这段代码解决了这个问题:

      this.router.events.subscribe(event => {
          if (event instanceof RoutesRecognized) {
              console.log(event.state.root.firstChild.data['a']);
           }
      });
      

      【讨论】:

        【解决方案5】:

        IMO 要获取 routeConfig,您需要路由器事件的 ActivationEnd 事件。我已经在路径中搜索了参数以通过这种方式进行比较:

        this.router.events.subscribe((event: any) => {
        if (event instanceof ActivationEnd) {
          const segmentArr = event.snapshot.routeConfig.path.split('/'); // there will be what you need
          const lastSegment = segmentArr.pop();
          // if the segment is not a param
          if (lastSegment.includes(':')) {
           // this is ":someparam" segment
          }
        }
        });
        

        【讨论】:

          【解决方案6】:

          您可以使用Router.state 获取原始Route 配置。

          由于children,Angular 路由器将当前路由表示为分层路由树,因此您需要遍历它以获取最深的子节点,这通常是您正在寻找的。​​p>

          可以通过以下方式完成:

          let currentRoute = this.router.routerState.root;
          while (currentRoute.firstChild) {
              currentRoute = currentRoute.firstChild;
          }
          console.log(currentRoute.routeConfig); // returns `Route` object
          

          为了对更改做出反应,这应该在 this.router.events.subscribe(...) 内。

          【讨论】:

            猜你喜欢
            • 2021-12-09
            • 2018-06-17
            • 2016-04-22
            • 2016-09-02
            • 1970-01-01
            • 2017-02-11
            • 1970-01-01
            • 1970-01-01
            • 2018-12-22
            相关资源
            最近更新 更多