typescript Angular Router Events: NavigationEnd -- 如何只过滤最后一个事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49722369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:20:31  来源:igfitidea点击:

Angular Router Events: NavigationEnd -- How to filter only the last event

angulartypescriptangular-routing

提问by Lynx 242

I want to extract only the last event entry of type NavigationEndfrom 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.

我只想从 router.events 中提取NavigationEnd 类型的最后一个事件条目。但不知何故,我找不到合适的方法来做到这一点。无论我尝试什么,以下代码都是访问这些感兴趣的对象的唯一方法。

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

但是我真的必须使用 .forEach() 让它运行所有条目并使用最后一个条目吗?有没有更好的方法来处理事件作为一种数组然后说

ne = arrayOfEvents[arrayOfEvents.length-1]

?

?

I'm getting crazy about it but it seems that I can't see the wood for the trees...

我对此很着迷,但似乎只见树木不见森林......

回答by Simon_Weaver

PS. There's a better way to filter using an instanceof typeguard, you then get the proper type without having to assert it again:

附注。有一种更好的方法可以使用instanceof typeguard进行过滤,然后您无需再次断言即可获得正确的类型:

firstChildData$ = this.router.events.pipe(

            filter((e): e is NavigationEnd => e instanceof NavigationEnd), 

            map(e => { // e is now NavigationEnd }

enter image description here

在此处输入图片说明

回答by Lynx 242

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.

感谢所有分享评论以支持我的人!它帮了我很大的忙,因为我能够把松散的东西绑起来。