Angular router可选参数destroy / init component

时间:2017-06-18 08:50:24

标签: angular angular2-routing

我正在使用@ angular / router

我的路线:

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

}

是否可以选择在没有destory / init MyComponent

的情况下在两个状态('',':id')之间导航

例如:

url:空的, 致电ngOnInit()

网址:/some_id, 调用ngOnDestory()ngOnInit()(销毁/构建MyComponent)

1 个答案:

答案 0 :(得分: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
        }
    });
}