Angular 2:如何从Component中读取延迟加载的Module的路由

问题描述 投票:0回答:2

我正在开发一个应用程序,它分为多个模块,这些模块是延迟加载的。在每个模块上:

  • 我定义了一组子路由。
  • 根据当前路线,有一个“基础”组件具有加载相应组件的<router-outlet>

我希望能够从该基本组件访问与该模块对应的所有子路由及其“数据”属性。

这是一个简单的例子。你可以在this 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>

电影,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注入组件,但这些似乎都没有我需要的信息。

angular angular2-routing
2个回答
1
投票

试试这个

 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);
  }
}

它不会是懒惰的路线。

© www.soinside.com 2019 - 2024. All rights reserved.