georgeos
georgeos

Reputation: 2501

Detect navigation back from component in named router outlet

I display an A Component in a router-outlet and inside this I have another B Component which has a named router-outlet, where I display another C component.

Router-outlet
A Component
    B Component
    Named Router-outlet
        C Component

In this C Component, I perform a validation, after this, I want to go back into the A Component reloading it (executing ngOnInit or any method).

I have tried it using different methods, like navigate, navigateByUrl and Location.back(). The problem is that the A Component is never destroyed, therefore it's never executed the ngOnInit method.

Somebody know how can I solve this? Thanks!

Upvotes: 1

Views: 660

Answers (2)

Eitan Seri-Levi
Eitan Seri-Levi

Reputation: 341

You can create a service to handle this specific situation

   export class RefreshService{   
       private refreshMessage = new BehaviorSubject<any>(null);        
       refreshObservable = this.refreshMessage.asObservable();

       sendRefreshMessage() {
         this.refreshMessage.next("");
       }
    }

In component A I subscribe to my observable

export class AComponent implements OnInit {

  constructor(private refreshService: RefreshService) { }

  ngOnInit() {
   this.refreshService.subscribe(res => { do stuff here } );
  }

}

In component C after you perform your validation :

this.refreshService.sendRefreshMessage();

This will trigger your subscription in component A, all code inside the subscription will then be executed

Upvotes: 1

Lars
Lars

Reputation: 788

I'm not quite sure how you'll be able to execute the ngOnInit again, but a workaround could be to subscribe to router events (as described here) and execute the code you want in there.

Upvotes: 1

Related Questions