我正在使用Angular 5,我似乎无法使用我问题的其他答案中所述的方法从ActivatedRoute获取数据。
app.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或未定义的路径获取数据
答案 0 :(得分:4)
问题是您不是在您尝试查看的路线。你需要经过儿童路线。这里有一个例子: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);
});
通过这段代码,我得到了这个:
答案 1 :(得分:0)
我能够在这个github问题之后解决我的问题:https://github.com/angular/angular/issues/11812
this.router.events.subscribe((data) => {
if (data instanceof RoutesRecognized) {
console.log(data.state.root.firstChild.data);
}
});