当相同组件加载不同数据时,不会调用ngOnInit

San*_*rma 9 angular2-routing angular

我有一个有角度的2应用程序,我使用路由器在视图之间导航,就像其他人一样.以下是我的特定组件的路径:

{
    path: 'home/view1/:viewID',
    component: ViewComponent,
    children: [
        { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent },
        { path: '**', component: ViewEditComponent }
    ]
},
Run Code Online (Sandbox Code Playgroud)

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

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

ViewComponent模板:

   <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>
Run Code Online (Sandbox Code Playgroud)

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

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

Gün*_*uer 10

注入路径并订阅参数更改

constructor(route:ActivatedRoute) {
  route.params.forEach(params => {
    myInit(params['paramId']);
  });
}
Run Code Online (Sandbox Code Playgroud)


His*_*dow 6

只是想补充一点,如果您在组件加载之前使用路由解析器来获取数据,那么您可以将以下代码放在组件的ngOnInit方法中:

ngOnInit(){
    this.activatedRoute.data.subscribe(data => {
         initData(data['mydata']);
    });
}

initData(data){
    // process new data
}
Run Code Online (Sandbox Code Playgroud)

现在,只要解析器更新路径的已解析数据,组件的模型就会更新并显示新数据.