Angular2學習筆記——在子組件中拿到路由參數

原文鏈接:http://www.cnblogs.com/dojo-lzz/p/5883408.html

  工作中碰到的問題,特此記錄一下。

  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瞭解並不深入,無法給出詳細解釋,待我深入瞭解後,再寫一篇關於路由的文章奉獻給大家。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章