读取路径参数angular2

时间:2017-02-10 19:30:13

标签: angular components angular2-routing

我有两个组件,我想使用路由参数将变量从一个发送到另一个。在我的第一个组件中,我使用此函数发送id:

sendId(id : string) : void {
    this.router.navigate(['/component2', id]);
}

我的路由模块如下所示:

const routes: Routes = [
 { path: 'component2/:id', component: Component2},
 { path: '**', redirectTo: '' }
];

@NgModule({
 imports: [ RouterModule.forRoot(routes) ],
 exports: [ RouterModule ]
})

export class AppRoutingModule {}

在我的第二部分中,我试图像这样阅读:

import { Router, ActivatedRoute, Params } from '@angular/router';

export class Component2 implements OnInit {
   id: string;

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

ngOnInit() {
    this.route.params.subscribe(params => { this.id = +params['id']; 
    });

    console.log(this.id);
}

但我收到一个空值。我错过了什么?

2 个答案:

答案 0 :(得分:5)

因为console.log(this.id);在从路线获取值之前有效。将console.log放入subscribe函数

ngOnInit() {
    this.route.params.subscribe(params => { 
        this.id = +params['id']; 
        console.log(this.id);
    });  
}

答案 1 :(得分:1)

我设法通过更改我的component2代码来实现:

import { Router, ActivatedRoute, Params } from '@angular/router';

export class Component2 implements OnInit {
   id: string;
   private sub: any;    <---- add subcriber

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

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];   <---- remove '+'
});

console.log(this.id);
}

我添加了订阅者并从params ['id']

中删除了'+'