I would like to obtain a list of all Angular router events which were fired during the navigation to a particular view. Yes, I understand in most cases this will be the same.
I know how to subscribe to router events. So my code would look like something like this?
router.events
.pipe(
// toArray() maybe?
takeUntil(), // NavigationEnd, NavigationCancel, NavigationError
)
.subscribe();
This is probably just basic rxjs and my mind is bypassing an obvious answer.
3
Fist create a service property that stores the array, this array will store the events.
Then in app component listen for the events and push it into the array.
router.events
.subscribe((event: any) => this.someService.eventArr.push(event));
Then when you navigate to the route, reset the array to empty and then trigger the navigation.
When you access the array on the component, you will have the full list.
With your approach, it gets called only on component load (A lot of events are lost), so it wont be the full list, this will provide the full list of events.
Router events observable does not complete, it continuously provides values, so unsubscribing on component destroy is essential.
Basically, you are on the right track. If you want to filter out a few router events, you can use filter()
operator and then you can use toArray()
. The takeUntil()
can be used to stop the subscription of router events.
As Naren mentioned above, they do no stop, you need to manually stop it or filter it based on your needs.
This is a sample of how you can do that:
import { NavigationEnd, NavigationCancel, NavigationError, Event } from '@angular/router';
import { filter, takeUntil, toArray } from 'rxjs/operators';
import { Subject } from 'rxjs';
// Create a subject that emits when the navigation ends
const navigationEnd = new Subject<Event>();
router.events.pipe(
// Filter for the router events you're interested in
filter(
event =>
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
),
// Gather all the events into an array
toArray(),
// Complete the observable when a NavigationEnd, NavigationCancel, or NavigationError event occurs
takeUntil(navigationEnd)
).subscribe(events => {
console.log(events); // This will log an array of all the router events
});
// In your navigation end logic
router.events.pipe(
filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError),
).subscribe(event => {
navigationEnd.next(event);
});