Angular 2:从父组件获取 RouteParams [英] Angular 2: getting RouteParams from parent component

查看:29
本文介绍了Angular 2:从父组件获取 RouteParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从父组件获取 RouteParams?

How do I get the RouteParams from a parent component?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'Home'},
  {path: '/:username/...', component: ParentComponent, as: 'Parent'}
])

export class HomeComponent {
  ...
}

然后,在 ParentComponent 中,我可以轻松获取我的用户名参数并设置子路由.

And then, in the ParentComponent, I can easily get my username param and set the child routes.

Parent.ts:

@Component({
  ...
})

@RouteConfig([
  { path: '/child-1', component: ChildOneComponent, as: 'ChildOne' },
  { path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' }
])

export class ParentComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
  }

  ...
}

但是,如何在这些子组件中获得相同的用户名"参数?做和上面一样的把戏,不做.因为这些参数是在 ProfileComponent 中定义的??

But then, how can I get this same 'username' parameter in those child components? Doing the same trick as above, doesn't do it. Because those params are defined at the ProfileComponent or something??

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
    // returns null
  }

  ...
}

推荐答案

更新:

现在Angular2 final已经正式发布,正确的做法如下:

Now that Angular2 final was officially released, the correct way to do this is the following:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.sub = this.route.parent.params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

<小时>

原文:

这是我如何使用@angular/router":3.0.0-alpha.6"包:

Here is how i did it using the "@angular/router": "3.0.0-alpha.6" package:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

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

    ngOnInit() {
        this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

在这个例子中,路由的格式如下:/parent/:id/child/:childid

In this example the route has the following format: /parent/:id/child/:childid

export const routes: RouterConfig = [
    {
        path: '/parent/:id',
        component: ParentComponent,
        children: [
            { path: '/child/:childid', component: ChildComponent }]
    }
];

这篇关于Angular 2:从父组件获取 RouteParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆