我正在开发一个应用程序,该应用程序被分成多个模块,这些模块是延迟加载的。在每个模块上:
<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>
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
注入组件,但是这些似乎都不具备我需要的信息。
答案 0 :(得分:1)
尝试
constructor(private route: ActivatedRoute) {
console.log(this.route.routeConfig.children);
}
答案 1 :(得分:-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);
}
}
其中不会有延迟加载的路由。