2017-04-06 35 views
3

我有这样的结构,我app.component.html角路由器从根组件让孩子PARAM

<app-main-nav></app-main-nav> 
<router-outlet></router-outlet> 

这是我的路线:

const routes = [ 
    {path: "", redirectTo: "home", pathMatch: "full"}, 
    { 
    path: "posts", component: PostsComponent, 
    children: [{ 
     path: ":id", 
     component: PostComponent 
    }]; 
    } 
] 

我试图从PostComponent访问PARAMS页面在我的MaiNavComponent,但它会引发错误。

export class MainNavComponent implements OnInit { 

    constructor(private route: ActivatedRoute) { 
    route.params.subscribe(console.log) 
    } 
} 

我怎样才能获得PostComponentMainNavComponent:id

我试着这样做:

route.params.subscribe(console.log) 

在这里,我得到一个对象。

这:

route.firstChild.params.subscribe(console.log) 

无法读取空

回答

1

的问题是,在出口(route-outlet)加载ActivatedRoute唯一可用的内部组件的特性 'PARAMS'。在外部组件,你可以注入路由器,并用它如下:

export class MainNavComponent implements OnInit { 

    constructor(private router: Router) {} 

    ngOnInit() { 

     // Fires when the url changes 
     this.router.events.subscribe(data => { 
      // Only handle final active route 
      if (data instanceof NavigationEnd) { 

       // parsedUrl conatins params, queryParams 
       // and fragments for the active route 
       let parsedUrl = this.router.parseUrl(this.router.url); 

       console.log(parsedUrl); 
      } 
     }); 
    } 
} 

我希望这会帮助你。

+0

它不工作。 – undefined

+0

@undefined是否有错误? –

+0

不,但参数是空的 – undefined

0

你必须快照从URL.Uodate构造函数获取ID下面

constructor(private route: ActivatedRoute) { 
    } 
ngOnInit() { 
    // (+) converts string 'id' to a number 
    let id = +this.route.snapshot.params['id']; 


}