从子组件导航时更新父组件(角度)
问题描述:
我在从子组件路由时更新父组件时遇到了一些问题。我通过研究发现了这么多,是否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()
和getSomething2()
当用户从子组件DetailComponent
路由回DashboardComponent
。
感谢您的帮助!
答
解决此问题的方法是使用主题。
在DashboardComponent你可以声明一个主题:
public static returned: Subject<any> = new Subject();
和订阅它:
constructor() {
DashboardComponent.returned.subscribe(res => {
this.getSomething1(); // this populates an array
this.getSomething2();
});
}
在DetailComponent,删除项目后,您拨打的主题下:
deleteItem(item: any) {
// some code...
DashboardComponent.returned.next(false);
this._router.navigate(['dashboard']);
}
谢谢,这个作品很有魅力!只需将'DetailComponent.returned.next(false)'改为'DashboardComponent.returned.next(false)',我将接受答案! :)感谢一堆! – Alex
不用担心@ASomeOneJ!只是改变了错误。 –