When the NavigationEnd
event is emitted, it retrieves the current navigation state using this.router.getCurrentNavigation()
. If there is a navigation state available in the extras property of the navigation object, it logs the state to the console.
constructor(
private router: Router,
private activeRoute: ActivatedRoute
) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
takeUntil(this.unsubscribe$)
)
.subscribe((event) => {
const navigation = this.router.getCurrentNavigation();
if (navigation && navigation.extras.state) {
console.log(navigation.extras.state);
}
});
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
Explanation from ChatGPT:
The this.router.events
property represents an observable that emits
events related to navigation in the router.
The pipe method allows you to chain multiple operators to the observable.
In this case, the filter operator is used to only allow NavigationEnd
events to pass through. This ensures that the code inside the subscribe callback is only executed when a navigation ends.
The takeUntil operator is used to complete the observable when the this.unsubscribe$
subject emits a
value. This is done to clean up the subscription when the component
is destroyed.
Finally, inside the subscribe callback, the current
navigation state is retrieved using
this.router.getCurrentNavigation()
. If there is a navigation state
available and it has a state property in the extras object, the state
is logged to the console.
NB: In the ngOnDestroy
method, the this.unsubscribe$.next()
method is called to emit a value and complete the this.unsubscribe$
subject, which will in turn complete the takeUntil
operator and unsubscribe from the router events.
Optimize Code:
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
take(1) // Only take the first event
)
.subscribe((event) => {
const navigation = this.router.getCurrentNavigation();
if (navigation && navigation.extras.state) {
console.log(navigation.extras.state);
}
});