在从子组件进行路由时,我在更新父组件时遇到了一些问题。我通过研究发现,ngOnInit只会被调用一次,但是如何解决这个问题呢?我尝试过不同的生命周期挂钩,但要么我无法正确地使用它们,要么我根本不应该使用它们!有人能帮忙吗?谢谢!
我的路线:
{
path: 'dashboard',
component: DashboardComponent,
children: [
{
// when user is on dashboard component, no child component shown
path: '',
},
{ // detail component
path: ':table/:id', //
component: DetailComponent,
},
//some more child routes and components...
]
}仪表板组件中的ngOnInit (父组件)
ngOnInit() {
this.getSomething1(); // this populates an array
this.getSomething2(); // this populates an array
}当用户从上面的数组中选择一个项时,用户将被路由到该项(DetailComponent)的详细页,在该页面中,用户可以更新/删除该项。
在子组件中,当用户删除项时,用户将被路由到父组件:
deleteItem(item: any) {
// some code...
this._router.navigate(['dashboard']);
}因此,所有这些操作都很好,只是没有更新项目数组,因为ngOnInit只被调用了一次。
因此,当用户从子组件getSomething1()被路由回DashboardComponent时,我想运行方法DashboardComponent和DetailComponent。
谢谢你的帮助!
发布于 2016-12-17 11:38:41
解决这种情况的方法是使用主语。
在DashboardComponent中,您可以声明一个主题:
public static returned: Subject<any> = new Subject();并订阅:
constructor() {
DashboardComponent.returned.subscribe(res => {
this.getSomething1(); // this populates an array
this.getSomething2();
});
}在DetailComponent中,删除项目后,在主题中调用next:
deleteItem(item: any) {
// some code...
DashboardComponent.returned.next(false);
this._router.navigate(['dashboard']);
}https://stackoverflow.com/questions/41197732
复制相似问题