'Angular Router Events: NavigationEnd -- How to filter only the last event
I want to extract only the last event entry of type NavigationEnd from router.events. But somehow I can't find a proper way to do this. Whatever I try the following code snipped is the only way to get access to these objects of interest.
let ne: any;
router.events.filter(e => e instanceof NavigationEnd)
.forEach(e => {
ne = e as NavigationEnd;
});
console.log('target page: ', ne.urlAfterRedirects);
But do I really have to use .forEach() letting it run though all entries and using then the last entry? Isn't there a better way to handle the events as a kind of array and then say
ne = arrayOfEvents[arrayOfEvents.length-1]
?
I'm getting crazy about it but it seems that I can't see the wood for the trees...
Solution 1:[1]
PS. There's a better way to filter using an instanceof typeguard, you then get the proper type without having to assert it again:
this.firstChildData$ = this.router.events.pipe(
filter((e): e is NavigationEnd => e instanceof NavigationEnd),
map(e => {
// e is now NavigationEnd
})
);
Solution 2:[2]
If you are using ngrx effect then you can create a effect that listen to router event:
import { NavigationEnd, Router } from '@angular/router';
routeTo$ = createEffect(
() =>
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
withLatestFrom(this.observable1$, this.observable1$),
tap(([routerEvent, observable11Value, observable12Value]) => {
if (this.router.url.includes(observable11Value) && !this.router.url.includes(observable12Value)) {
this.router.navigate([`/home/${observable11Value}`]);
}
})
),
{ dispatch: false }
);
Solution 3:[3]
this.router.events.subscribe(value => {
if(value instanceof NavigationEnd)
console.log(this.router.url.toString());
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rofrol |
| Solution 2 | Sukhminder Sandhu |
| Solution 3 | ebey |

