简体   繁体   English

读取路径参数angular2

[英]Read route parameter angular2

I have two components and i want to send a variable from one to the other using a route parameter. 我有两个组成部分,我想使用route参数将变量从一个发送到另一个。 In my first component I use this function to send the id: 在我的第一个组件中,我使用此函数发送ID:

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

My routing module looks like this: 我的路由模块如下所示:

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

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

export class AppRoutingModule {}

And in my second component I'm trying to read it like this: 在第二个组件中,我试图像这样阅读它:

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

But I receive a null value. 但是我收到一个空值。 What am i missing? 我想念什么?

Because console.log(this.id); 因为console.log(this.id); works before you get the value from the route. 在您从路线中获取价值之前起作用。 Put the console.log into the subscribe function console.log放入subscribe功能

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

I managed to do it by changing my component2 code like this: 我设法通过更改我的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);
}

I added the subscriber and removed the '+' from params['id'] 我添加了订阅者,并从params ['id']中删除了“ +”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM