ngOnInit not called when same component is loaded with different data

心已入冬 提交于 2019-12-10 02:22:49

问题


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 }
    ]
},

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

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

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>

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?


回答1:


Inject the route and subscribe to parameters change

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



回答2:


Just wanted to add that if you're using a route resolver to get data before the component loads then you can put the following code in your component's ngOnInit method:

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

initData(data){
    // process new data
}

Now whenever your resolver updates the route's resolved data your component's model will get updated and display the new data.




回答3:


For the same instance of the component, ngOnInit() gets called once only.




回答4:


I had a similar issue with ngOnInit not being called on route change. I moved the code to ngAfterViewInit() and it worked.



来源:https://stackoverflow.com/questions/39962857/ngoninit-not-called-when-same-component-is-loaded-with-different-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!