ddhille
ddhille

Reputation: 137

Retrieve routes from lazily loaded routing.module into child component without creating a circular dependency

Scenario

What I want to achieve

How it currently looks like

app-routing.module.ts (partially)

...
export const routes: Routes = [
...
  {
    path: 'admin',
    loadChildren: () => import('./pages/admin/admin.module').then(m => m.AdminModule),
    canActivate: [AuthGuard],
    data: {
      title: 'Administration',
      icon: 'grade',
      label: 'ADMIN',
      labelAddition: ''
    }
  },
...
]
...

admin-routing.module.ts (partially)

...
export const routes: Routes = [
...
  {
    path: '',
    component: AdminComponent
  },
...
]
...

admin.component.ts

import { Component } from '@angular/core';
import { routes } from './admin-routing.module';

@Component({
  template: `<app-sub-nav [links]="links"></app-sub-nav>`
})
export class AdminComponent {
  links = routes;
  constructor() { }
}

sub-nav.component.html (partially)

...
<a *ngFor="let link of links" [routerLink]="['./' + link.path]">
...

What's the problem?

Circular dependency detected:
src\app\pages\admin\admin-routing.module.ts -> src\app\pages\admin\admin.component.ts -> src\app\pages\admin\admin-routing.module.ts

What did I try so far?

admin-routing.module.ts (partially)

...
export const routes: Routes = [
...
  {
    path: '',
    component: AdminComponent,
    data: {
      routes: [
      {
        path: '...',
        data: {
         icon: '...'
...
        }
...
      },
...
      ]
    }
  },
...
]
...

Any ideas?

Upvotes: 1

Views: 192

Answers (1)

Eldar
Eldar

Reputation: 10790

If i correctly understand the situation : You want to populate your navigation with links from lazily loaded and guarded module. So you want to access the route of the lazily loaded module to build your side navigation. What i would suggest is to create a service called NavigationService in root scope. Make this navigation service that is responsible for keeping the track of navigation links. Provide methods add remove links and event (more likely observables) like navigationChanged. In your lazy module import that service and call add method to add links and in your side panel component import the same service and subscribe the navigationChanged event to modify your navigation layout.

Upvotes: 1

Related Questions