Scenario
We want to centrally track all angular NavigationEnd
events for analytical purposes and document Title
and Meta
tag update purposes.
Approach
Inside app.component.ts
perform the event tracking in the constructor
like this:
constructor(private router:Router) {
const events =
router.events.
pipe( filter(event=>event instanceof NavigationEnd));
events.subscribe((e:NavigationEnd)=>{
console.log(e.urlAfterRedirects)
})
}
Note that the AppComponent
gets created only once during the applications life time, thus we do not need to worry about unsubscribing
from the router Observable
.
Angular 12+
After Angular 12 the following will do the trick:
const events =
router.events.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
map((event: NavigationEnd) => event.url))
Updating to this will avoid the error:
Argument of type 'MonoTypeOperatorFunction<Event_2>' is not assignable to parameter of type 'OperatorFunction<Event_2, NavigationEnd>'.
Type 'Observable<Event_2>' is not assignable to type 'Observable'.
Type 'Event_2' is not assignable to type 'NavigationEnd'.
Property 'urlAfterRedirects' is missing in type 'RouterEvent' but required in type 'NavigationEnd'.ts(2345)