当同一组件加载了不同的数据时,不会调用ngOnInit [英] ngOnInit not called when same component is loaded with different data

查看:102
本文介绍了当同一组件加载了不同的数据时,不会调用ngOnInit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angle 2应用程序,并且像其他所有人一样,我使用router在视图之间导航.这是我特定组件的路径:

I have an angular 2 app, and I use router to navigate between views, like everyone else. Here is how my path for a particular component look like:

{
    path: 'home/view1/:viewID',
    component: ViewComponent,
    children: [
        { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent },
        { path: '**', component: ViewEditComponent }
    ]
},

现在,我在ViewComponent上有两个按钮,分别为section1和section2加载SectionEditComponent.

Now, I have two buttons on the ViewComponent, to load SectionEditComponent for section1 and section2.

路径1:pane/1/section/1
路径2:pane/1/section/2

Path1: pane/1/section/1
Path2: pane/1/section/2

ViewComponent模板:

ViewComponent template:

   <div class="col-md-8" style="background-color: white; height: 100%">
       <button (click)="loadPath(1)">Path1</button>
       <button (click)="loadPath(2)">Path2</button>
       <router-outlet></router-outlet>
   </div>

现在,当我从同一ViewComponent中的Path1-> Path2或Path2-> Path1导航时,不会调用ngOnInit(),因此即使URL实际上根据新的部分ID进行了更改,也不会加载新路径.

Now, when I navigate from Path1->Path2 or Path2->Path1 within same ViewComponent, the ngOnInit() is not called, thus not loading the new path, even though the url actually change according to the new section ID.

这是已知行为还是预期行为?我在做错什么吗?

Is this known or expected behavior? Is there anything that I'm doing wrong?

推荐答案

注入路由并订阅参数更改

Inject the route and subscribe to parameters change

constructor(route:ActivatedRoute) {
  route.params.forEach(params => {
    myInit(params['paramId']);
  });
}

这篇关于当同一组件加载了不同的数据时,不会调用ngOnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆