2017-04-06 111 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']; 


}