问题
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...
回答1:
PS. There's a better way to filter using a 'typeguard', you then get the proper type without having to assert it again:
firstChildData$ = this.router.events.pipe(
filter((e): e is NavigationEnd => e instanceof NavigationEnd),
map(e => { // e is now NavigationEnd }
This is actually necessary in strict mode.
回答2:
Okay, after reading through the posted articles above and rethinking what I really want to achieve I found out that my approach was definitely too complicated. Because actually I only need access to the currently called route. And so I started from scratch and came across this small but very effective solution:
this.router.events.subscribe(value => {
console.log('current route: ', router.url.toString());
});
Thanks to all who shared a comment in oder to support me! It helped al lot as I was able to tie up loose ends.
来源:https://stackoverflow.com/questions/49722369/angular-router-events-navigationend-how-to-filter-only-the-last-event