【问题标题】:Angular2 get activated route parameters and parent parametersAngular2获取激活的路由参数和父参数
【发布时间】:2017-01-10 09:10:59
【问题描述】:

如何从父组件和子路由中获取 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']);
    });
}
}

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

提前致谢。

【问题讨论】:

  • 您找到解决方案了吗?我也有同样的问题。
  • 尚未寻找解决方案
  • 对我来说,我意识到我在 router-outlet 之外的组件中调用了 ActivatedRoute。这就是我收到undefined 的原因。将组件移动到内部 router-outlet 解决了我的问题。

标签: angular angular2-routing angular2-components


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    import { ActivatedRoute } from '@angular/router';
    
      constructor(private route: ActivatedRoute) {
            const taskId: string = route.snapshot.params["taskId"];
            console.log("this is taskId value = "+ taskId);
        }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-01-15
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        • 1970-01-01
        • 2017-05-24
        相关资源
        最近更新 更多