Angular 当同一组件加载了不同的数据时,不会调用ngOnInit
我有一个angular 2应用程序,和其他人一样,我使用路由器在视图之间导航。以下是特定组件的路径:Angular 当同一组件加载了不同的数据时,不会调用ngOnInit,angular,angular2-routing,Angular,Angular2 Routing,我有一个angular 2应用程序,和其他人一样,我使用路由器在视图之间导航。以下是特定组件的路径: { path: 'home/view1/:viewID', component: ViewComponent, children: [ { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent }, { path: '**', component:
{
path: 'home/view1/:viewID',
component: ViewComponent,
children: [
{ path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent },
{ path: '**', component: ViewEditComponent }
]
},
现在,我在ViewComponent上有两个按钮,用于为section1和section2加载SectionEditComponent
路径1:窗格/1/节/1路径2:窗格/1/节/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>
路径1
路径2
现在,当我在同一个ViewComponent中从Path1->Path2或Path2->Path1导航时,不会调用ngOnInit(),因此不会加载新路径,即使url实际上会根据新的节ID更改
这是已知的还是预期的行为?有什么我做错了吗?对于相同的组件实例,
ngOnInit()
只被调用一次。注入路由并订阅参数更改
constructor(route:ActivatedRoute) {
route.params.forEach(params => {
myInit(params['paramId']);
});
}
只是想补充一点,如果在加载组件之前使用路由解析器获取数据,那么可以在组件的ngOnInit方法中添加以下代码:
ngOnInit(){
this.activatedRoute.data.subscribe(data => {
initData(data['mydata']);
});
}
initData(data){
// process new data
}
现在,每当您的解析器更新路由的已解析数据时,您的组件模型将得到更新并显示新数据。我遇到了一个类似的问题,即在路由更改时没有调用ngOnInit。
我将代码移动到了ngAfterViewInit(),它成功了。谢谢,那么如何实现重新加载呢?(或者如果每次都调用任何其他方法)但您到底想要实现什么?实际上,我有一个基于路由参数的组件初始化逻辑@Günter Zöchbauer的答案正是我想要的()我得到了
错误:expressionchangedferithasbeenCheckedError:表达式在被检查后发生了变化。上一个值:“true”。当前值:“false”。
执行此操作时。另外,在重用组件时,它没有触发两次,因此我不确定它是否有效。@TetraDev这可能会帮助您: