Angular Router Events: NavigationEnd -- 如何只过滤最后一个事件 [英] Angular Router Events: NavigationEnd -- How to filter only the last event

查看:15
本文介绍了Angular Router Events: NavigationEnd -- 如何只过滤最后一个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

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

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...

推荐答案

好吧,在阅读了上面发布的文章并重新思考我真正想要实现的目标后,我发现我的方法绝对太复杂了.因为实际上我只需要访问当前调用的路由.所以我从头开始,遇到了这个小但非常有效的解决方案:

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: ', this.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.

这篇关于Angular Router Events: NavigationEnd -- 如何只过滤最后一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆