Angular 2:如何从组件中读取惰性加载模块的路由

3

我正在开发一个应用程序,它被分成多个模块,并且采用了懒加载。在每个模块中:

  • 我定义一组子路由。
  • 有一个“基础”组件,它具有使用<router-outlet>加载相应组件的功能,根据当前路由进行加载。

我希望从该基础组件中访问对应于模块的所有子路由及其“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 { }

是否有办法从同一个模块的组件中获取子路由的数据属性?

我尝试了将RouterActivatedRoute注入到组件中,但是这些都没有我需要的信息。

2个回答

4

试一试

 constructor(private route: ActivatedRoute) { 
    console.log(this.route.routeConfig.children);
 }

-1

你可以通过 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);
  }
}

它不会有惰性加载的路由。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接