Angular 从子组件(角度)导航时更新父组件
从子组件路由时,我在更新父组件时遇到一些问题。我通过研究发现,ngOnInit只会被调用一次,但如何解决这个问题呢?我尝试过不同的生命周期挂钩,但要么我不能正确使用它们,要么我根本不应该使用它们!有人能帮忙吗?谢谢 我的路线:Angular 从子组件(角度)导航时更新父组件,angular,typescript,Angular,Typescript,从子组件路由时,我在更新父组件时遇到一些问题。我通过研究发现,ngOnInit只会被调用一次,但如何解决这个问题呢?我尝试过不同的生命周期挂钩,但要么我不能正确使用它们,要么我根本不应该使用它们!有人能帮忙吗?谢谢 我的路线: { path: 'dashboard', component: DashboardComponent, children: [ { // when user is on dashboard component
{
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(父级)
当用户从上面的一个数组中选择一个项目时,用户将被路由到该项目的详细信息页面(DetailComponent),在该页面中用户可以更新/删除该项目
方法,当用户删除项时,用户将被路由到parentcomponent:
deleteItem(item: any) {
// some code...
this._router.navigate(['dashboard']);
}
因此,所有这些都可以正常工作,只是项数组没有得到更新,因为ngOnInit只被调用一次
因此,当用户从子组件DetailComponent
路由回DashboardComponent
时,我想运行方法getSomething1()
和getSomething2()
谢谢你的帮助 解决这种情况的方法是使用主题 在仪表板组件中,您可以声明主题:
public static returned: Subject<any> = new Subject();
在DetailComponent中,删除项目后,调用subject中的next:
deleteItem(item: any) {
// some code...
DashboardComponent.returned.next(false);
this._router.navigate(['dashboard']);
}
谢谢,这个很有魅力!只需将
DetailComponent.returned.next(false)
更改为DashboardComponent.returned.next(false)
,我将接受答案!)非常感谢!!别担心@ASomeOneJ!只是改变了错误。
constructor() {
DashboardComponent.returned.subscribe(res => {
this.getSomething1(); // this populates an array
this.getSomething2();
});
}
deleteItem(item: any) {
// some code...
DashboardComponent.returned.next(false);
this._router.navigate(['dashboard']);
}