【问题标题】:Angular router optional params destroy/init component角路由器可选参数销毁/初始化组件
【发布时间】:2017-06-18 08:50:23
【问题描述】:

我正在使用@angular/路由器

我的路线:

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

}

是否有任何选项可以在没有 destory/init MyComponent 的情况下在两种状态('', ':id')之间导航

例如:

网址:空, 拨打ngOnInit()

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

【问题讨论】:

  • 是的。你想做什么no parameterid = 1 一些价值它应该如何表现。我的建议是改用两个不同的组件。
  • 我需要两个选项相同的组件...
  • @YairTawil 我明白你想说什么,我也有同样的问题。你能找到答案吗?

标签: angular angular2-routing


【解决方案1】:

您可以为此使用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
        }
    });
}

【讨论】:

  • 为什么?有什么正当理由吗??
  • 在我的应用程序上调用 ngOnInit 很昂贵。还是谢谢
  • 如果不是ngOnInit(),您将在哪里处理路由器更改??
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 2013-08-04
  • 1970-01-01
  • 2015-07-18
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
相关资源
最近更新 更多