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

前端之家收集整理的这篇文章主要介绍了angular2 – Angular 2:从父组件获取RouteParams前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从父组件获取RouteParams?

应用:

  1. @Component({
  2. ...
  3. })
  4.  
  5. @RouteConfig([
  6. {path: '/',component: HomeComponent,as: 'Home'},{path: '/:username/...',component: ParentComponent,as: 'Parent'}
  7. ])
  8.  
  9. export class HomeComponent {
  10. ...
  11. }

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

父母:

  1. @Component({
  2. ...
  3. })
  4.  
  5. @RouteConfig([
  6. { path: '/child-1',component: ChildOneComponent,as: 'ChildOne' },{ path: '/child-2',component: ChildTwoComponent,as: 'ChildTwo' }
  7. ])
  8.  
  9. export class ParentComponent {
  10.  
  11. public username: string;
  12.  
  13. constructor(
  14. public params: RouteParams
  15. ) {
  16. this.username = params.get('username');
  17. }
  18.  
  19. ...
  20. }

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

  1. @Component({
  2. ...
  3. })
  4.  
  5. export class ChildOneComponent {
  6.  
  7. public username: string;
  8.  
  9. constructor(
  10. public params: RouteParams
  11. ) {
  12. this.username = params.get('username');
  13. // returns null
  14. }
  15.  
  16. ...
  17. }
更新:

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

  1. export class ChildComponent {
  2.  
  3. private sub: any;
  4.  
  5. private parentRouteId: number;
  6.  
  7. constructor(private route: ActivatedRoute) { }
  8.  
  9. ngOnInit() {
  10. this.sub = this.route.parent.params.subscribe(params => {
  11. this.parentRouteId = +params["id"];
  12. });
  13. }
  14.  
  15. ngOnDestroy() {
  16. this.sub.unsubscribe();
  17. }
  18. }

原版的:

这里是如何使用“@ angular / router”:“3.0.0-alpha.6”包:

  1. export class ChildComponent {
  2.  
  3. private sub: any;
  4.  
  5. private parentRouteId: number;
  6.  
  7. constructor(
  8. private router: Router,private route: ActivatedRoute) {
  9. }
  10.  
  11. ngOnInit() {
  12. this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
  13. this.parentRouteId = +params["id"];
  14. });
  15. }
  16.  
  17. ngOnDestroy() {
  18. this.sub.unsubscribe();
  19. }
  20. }

在此示例中,路由具有以下格式:/ parent /:id / child /:childid

  1. export const routes: RouterConfig = [
  2. {
  3. path: '/parent/:id',children: [
  4. { path: '/child/:childid',component: ChildComponent }]
  5. }
  6. ];

猜你在找的Angularjs相关文章