2017-02-10 110 views
0

我有兩個組件,我想發送一個變量從一個到另一個使用路由參數。在我的第一部分我用這個功能來發送ID:閱讀路由參數angular2

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

但我收到一個空值。我錯過了什麼?

回答

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 [「身份證」刪除「+」 ]

4

因爲console.log(this.id);在您從路線獲取值之前有效。把console.logsubscribe功能

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

當我把console.log放在裏面的時候,我仍然得到null – Ayane