Angular2获取激活的路由参数和父参数

问题描述 投票:5回答:3

如何从父组件以及子路由获取RouteParams

export const routes: Routes = [
    { path: '', redirectTo: 'list', pathMatch: 'full' },
    { path: 'list', component: UsersComponent },
    {
        path: ':id', component: UserDetailComponent,
        children: [
            // { path: '', redirectTo: 'overview', pathMatch: 'full' },
            { path: 'overview', component: UserInfoComponent },
            { path: 'specs/:id', component: UserProfileComponent }
        ]
    }
];

在组件中

export class UserDetailComponent implements OnInit { 

constructor(private route: ActivatedRoute) { }
  ngOnInit() {
  this.route.parent.params.subscribe( (c) => {
        console.log(c['id']);
    });
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
}
}

但是当我的路线被激活时,我总是得到不确定。请帮助解决这个问题?

提前致谢。

angular angular2-routing angular2-components
3个回答
5
投票

这是一个简单的示例,如何在.ts中获取参数值,之后您将能够根据您的情况自定义此值

import { ActivatedRoute } from '@angular/router';

  constructor(private route: ActivatedRoute) {
        const taskId: string = route.snapshot.params["taskId"];
        console.log("this is taskId value = "+ taskId);
    }

4
投票

您需要ActivatedRouteSnapshot来遍历激活的路线。

https://angular.io/docs/ts/latest/api/router/index/ActivatedRouteSnapshot-interface.html


0
投票

var myParamValue = this.route.snapshot.queryParams['myParam'];

© www.soinside.com 2019 - 2024. All rights reserved.