Angular路由器从根组件获取子参数

时间:2017-04-06 15:56:05

标签: javascript angular router

我在app.component.html

中有这个结构
<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
    }];
  }
]

我正在尝试访问PostComponentMaiNavComponent页面中的参数,但会引发错误。

export class MainNavComponent implements OnInit {

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

如何从:id获取PostComponent的{​​{1}}?

我试着这样做:

MainNavComponent

我在这里得到一个对象。

而且:

 route.params.subscribe(console.log)
  

无法阅读财产&#39; params&#39;为null

3 个答案:

答案 0 :(得分:1)

问题是ActivatedRoute仅在插座(route-outlet)中加载的组件内可用。在外部组件中,您可以注入路由器并按如下方式使用它:

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);
            }
        });
    }
}

我希望这会对你有所帮助。

答案 1 :(得分:0)

constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
  this.loadParams();
}

private loadParams(): void {
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            let activatedRoute = this.activatedRoute.firstChild;
            while (!activatedRoute) {
                activatedRoute = activatedRoute.firstChild;
            }

            const value = activatedRoute.snapshot.paramMap.get('parmeter key');
        }
    });
}

答案 2 :(得分:-1)

您必须快照以从URL.Uodate构造函数获取ID,如下所示

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


}