Angular 2: Как читать маршруты лениво загруженного модуля из компонента - PullRequest
1 голос
/ 20 марта 2019

Я занимаюсь разработкой приложения, которое разделено на несколько модулей с отложенной загрузкой.Для каждого модуля:

  • Я определяю набор дочерних маршрутов.
  • Существует один «базовый» компонент, который имеет <router-outlet>, который загружает соответствующий компонент в соответствии с текущимroute.

Я хотел бы получить доступ от этого базового компонента ко всем дочерним маршрутам, которые соответствуют модулю, и их атрибутам «data».

Здесьпростой пример.Вы можете увидеть его в реальном времени на этом StackBlitz .

app.component.html

<router-outlet></router-outlet>

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'general'
  },
  {
    path: 'films',
    loadChildren: './films/films.module#FilmsModule'
  },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule { }

films.component.ts

@Component({
  selector: 'app-films',
  templateUrl: './films.component.html',
  styleUrls: ['./films.component.css']
})
export class FilmsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    // I'd like to have access to the routes here
  }
}

films.component.html

<p>Some other component here that uses the information from the routes</p>
<router-outlet></router-outlet>

films-routing.module.ts

const filmRoutes: Routes = [
  {
    path: '',
    component: FilmsComponent,
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'action' },
      { path: 'action',
        component: ActionComponent,
        data: { name: 'Action' }     // <-- I need this information in FilmsComponent
      },
      {
        path: 'drama',
        component: DramaComponent,
        data: {  name: 'Drama' }     // <-- I need this information in FilmsComponent
      },
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forChild(filmRoutes)
  ],
  exports: [
    RouterModule
  ],
})
export class FilmsRoutingModule { }

Есть ли способ получить атрибуты данных дочерних маршрутов из компонента в том же модуле?

Я пытался вставить Router и ActivatedRoute в компонент, но, похоже, ни в одном из них нет нужной мне информации.

Ответы [ 2 ]

1 голос
/ 20 марта 2019

попробуйте

 constructor(private route: ActivatedRoute) { 
    console.log(this.route.routeConfig.children);
 }
0 голосов
/ 20 марта 2019

Вы можете прочитать маршрут с router.config:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-films',
  templateUrl: './films.component.html',
  styleUrls: ['./films.component.css']
})
export class FilmsComponent implements OnInit {

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    console.log(this.router);
  }
}

Там не будет ленивых загруженных маршрутов.

...