2017-06-04 43 views
3

我想使用“product /:id”, 从类似于“sample.com/product/45”的链接中获取参数这里是我的路由声明:如何使用Angular 2中的“/:params”获取参数

export const routes: Routes = [ 
    { path: 'product/:id', component: Product } 
]; 

下面是组件类

export class Product implements OnInit, OnDestroy { 
    id: number; 
    private sub: any; 

    constructor(private route: ActivatedRoute) {} 

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

     console.log(this.id); //I get undefined here 
    }); 
    } 

    ngOnDestroy() { 
    this.sub.unsubscribe(); 
    } 
} 

当我试图CONSOLE.LOG()的ID,我得到未定义

+0

你看到路径参数吗? – Sajeetharan

+0

是的,它继续显示,当我访问链接 – Saad

+0

没有它进入ngOnit时,当你调试? – Sajeetharan

回答

2

试试这个,

ngOnInit() { 
    this.id = this.activatedRoute.snapshot.params["id"]; 
} 
相关问题