javascript - 從頂層組件中的延遲加載路由獲取自定義路由數據
我正在使用 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);
});
}
}
我似乎無法從路由中獲取數據,在 snapshot、root、children、firstChild 中,一切都是 null 或 undefined
答案#1
問題是你不在你試圖查看的路由上。你需要通過子路由。這裡有一個例子:使用 ActivatedRoute 在 Angular2 路由上檢索數據屬性,不論路由巢狀的層級如何。
我能夠使用上述連結中的資訊將你的程式碼修改如下。
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));
}
