工作中碰到的問題,特此記錄一下。
Angular2中允許我們以`path\:id\childPath`的形式來定義路由,比如:
export const appRoutes: RouterConfig = [{ path: 'app/:id', component: AppComponent, children: [ { path: 'share', component: AppShareComponent }, { path: 'issue', component: AppIssueComponent }, { path: 'version', component: AppVersionComponent }, { path: 'usage', component: AppUsageComponent }, { path: 'notification', component: AppNotificationComponent }, { path: 'resource', component: AppResourceComponent }, { path: 'comment', component: AppCommentComponent }, { path: 'activity', component: AppActivityComponent }, { path: 'retire', component: AppRetireComponent }, { path: '', component: AppComponent } ] }];
如果是在AppComponent中,很容易使用`ActivatedRoute`拿到當前路由獲取參數:
ngOnInit() { this.route.params.subscribe((params) => { this.createPies(); this.onTopListFilterChange(params['id']); }); };
但如果是在`children`中指定的component要拿到路由參數就沒那么容易了,這時候再使用ActivatedRoute根本拿不到參數,我猜應當是在Angular2中一個ActivatedRoute對應一級路由配置,所以我們需要找到父級路由,由父級路由去拿參數。這時我們需要借用Router類的routeState屬性的parent方法:
this.router.routeState.parent(this.activatedRoute).params.subscribe(params => { this.getDetailsById(params['id']); })
至此問題解決!
Angular2給我的感覺是大框架很清晰,細節太瑣碎,使用后端開發思維來做前端,過於冗余。目前對Angular2了解並不深入,無法給出詳細解釋,待我深入了解后,再寫一篇關於路由的文章奉獻給大家。