简体   繁体   中英

Update parent component when navigating from child Component (Angular)

I'm having some trouble with updating the parent component when routing from child component. This much I've found out by researching, is that ngOnInit only gets called once, but how to work around this? I've tried different lifecycle hooks, but either I've not been able to use them correctly or I should not use at all! Could someone please help? THANKS!

My routes:

{
    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 in dashboard component (parent)

ngOnInit() {
    this.getSomething1(); // this populates an array
    this.getSomething2(); // this populates an array
}

When user choses an item from one of the arrays above, user gets routed to detail page of that item (DetailComponent) where user can update/delete that item.

Method in child component, when user deletes item, user gets routed to parentcomponent:

deleteItem(item: any) {
    // some code... 
    this._router.navigate(['dashboard']); 
}

So all works fine, EXCEPT that the array of items does not get updated, since ngOnInit is called just once.

So I would like to run the methods getSomething1() and getSomething2() when user gets routed back to DashboardComponent from child component DetailComponent .

Thanks for any help!

A workaround to this situation is to use Subjects.

In the DashboardComponent you can declare a Subject:

public static returned: Subject<any> = new Subject();

And subscribe it:

constructor() {
      DashboardComponent.returned.subscribe(res => {
         this.getSomething1(); // this populates an array
         this.getSomething2();
      });
   }

In the DetailComponent, after deleting the item, you call next in the subject:

deleteItem(item: any) {
    // some code... 
    DashboardComponent.returned.next(false);
    this._router.navigate(['dashboard']); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM