我正在使用 Angular 5,我似乎无法使用我的问题的其他答案中所述的方法从 ActivatedRoute 获取数据。
应用程序.routes.ts
export const AppRoutes = [
{
path : '',
component: HomeView,
pathMatch: 'full', data: {key: 'home', label: 'Home'}},
{
path : 'about',
loadChildren: './+about/about.module#AboutModule'
},
{
path : 'account/:id',
loadChildren: './+account/account.module#AccountModule',
canActivate: [AuthGuard],
data: {key: 'account', label: 'My Account'}
},
];
app.component.ts
@Component({
selector: 'ou-app',
templateUrl: 'app.component.html',
styleUrls: ['../styles/main.scss'],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private route: ActivatedRoute,
){}
ngOnInit(){
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
console.log('router events console... ', this.route);
});
}
}
我似乎无法从快照、root、children、firstChild 下的路由中获取数据,一切都是 null 或 undefined
最佳答案
问题是您不在您要查看的路线上。您需要通过子路线。这里有一个例子:Retrieving a data property on an Angular2 route regardless of the level of route nesting using ActivatedRoute
我能够使用上述链接中的信息修改您的代码,如下所示。
router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
console.log(route.snapshot.data);
while (route .firstChild) route = route.firstChild;
return route;
})
.mergeMap(route => route.data)
.subscribe(x => {
console.log('router events console... ', x);
});
使用此代码,我能够得到:
更新:使用 RxJs v5.5 及更高版本
ngOnInit() {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
mergeMap((route) => route.data))
.subscribe((event) => console.log('router events console... ', event));
}
关于javascript - 从顶级组件中的延迟加载路由获取自定义路由数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49308304/