加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2 – Angular 2:从父组件获取RouteParams

发布时间:2020-12-17 08:43:07 所属栏目:安全 来源:网络整理
导读:如何从父组件获取RouteParams? 应用: @Component({ ...})@RouteConfig([ {path: '/',component: HomeComponent,as: 'Home'},{path: '/:username/...',component: ParentComponent,as: 'Parent'}])export class HomeComponent { ...} 然后,在ParentCompone
如何从父组件获取RouteParams?

应用:

@Component({
  ...
})

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

export class HomeComponent {
  ...
}

然后,在ParentComponent中,我可以很容易地获取我的用户名参数并设置子路由。

父母:

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

  ...
}

但是,那么,我如何在这些子组件中获得相同的“username”参数?做与上面相同的技巧,不这样做。因为那些参数是在ProfileComponent或者是?? ??

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

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

  ...
}
更新:

现在Angular2 final正式发布,正确的方法是这样做的:

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”包:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读