2017-06-18 53 views
0

我使用@角/路由器角路由器选购PARAMS破坏/初始化组件

我的路线:

{ 
     path: '', 
     component: MyComponent, 
    }, 
    { 
     path: ':id', 
     component: MyComponent 
    } 

} 

有任何选项,两个状态(“”,“之间导航:ID “)而不destory /初始化MyComponent

例如:

网址:空, 呼叫ngOnInit()

网址:/some_id, 通话ngOnDestory()ngOnInit()(破坏/建设为MyComponent)

+0

肯定。你想要做什么'无参数'和'id = 1'一些价值应该如何表现。我的建议是使用两个不同的组件。 – Aravind

+0

我需要两个选项相同的组件... – YairTawil

回答

0

可以使用ActivatedRoute注射器对于这一点,下面,

export default class MyComponent { 
    constructor(
    private route: ActivatedRoute, 
    private router: Router) {} 

    ngOnInit() { 
    this.sub = this.route 
    .params 
    .subscribe(params => { 
     if(params['id']){ 
      /// perform some opeartion with id 
     } else{ 
      // perform some other opeartion 
     } 
    }); 
} 
+0

我试图避免ngOnInit ... – YairTawil

+0

为什么?任何有效的原因?我的应用程序上的 – Aravind

+0

昂贵的调用ngOnInit。 无论如何感谢 – YairTawil