2

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!

1 Answer 1

3

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']); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works like a charm! Just change DetailComponent.returned.next(false) to DashboardComponent.returned.next(false) and I will accept the answer! :) Thanks a bunch!!
No worries @ASomeOneJ! Just changed the mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.