Angular2 - 检索当前网址 [英] Angular2 - retrieve current url

查看:66
本文介绍了Angular2 - 检索当前网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚更新到Angular 2.0.0-rc5,我当前页面网址的监听器似乎已被弃用。

I just updated to Angular 2.0.0-rc5 and my listener for the current page url seems to have been deprecated.

之前我可以通过订阅来访问它以下内容:

Previously I could access it by subscribing to the following:

constructor(private router: Router){
  router.subscribe(url => {
    if (url.instruction.routeName === 'Home'){
      this.home = true;
    }else{
      this.home = false;
    }
  });
}

当我更改页面时,它会输出存储在'name'字段中的内容对于路由器的每一页。

As I changed pages it would output what was stored in the 'name' field for each page of the router.

我已检查当前版本的路由器 ActivatedRoute 没有运气找到我可以订阅的东西,这将揭示数据,只有用冒号定义的参数。例如, site.com/user/:15 中的'15',当我想要的只是'用户'时。

I have checked through the current version of Router and ActivatedRoute with no luck finding something I can subscribe to that will reveal that data, only params defined with the colon. For example the '15' in site.com/user/:15 when all I want is 'user'.

Router.url 将返回我正在寻找的内容但不允许我订阅该数据以了解何时发生更改。

Router.url will return what I'm looking for but won't allow me to subscribe to that data to know when changes occur.

如何访问当前路径的路径名?

How do you access the current route's path name?

推荐答案

寻找 router.events 并订阅。典型的事件将是 NavigationEnd ,这将为您提供所需的网址信息。

Look for router.events and subscribe to that. The typical event will be NavigationEnd and this will give you the url information that you need.

router.events.subscribe(x => {
            if(x instanceof NavigationEnd) {
                console.log(x.url);
                console.log(x.urlAfterRedirects);
            }
        });

请注意,还有其他类型的事件,但基本方案使用 NavigationEnd

Note that there are other kind of events too, but the basic scenario uses NavigationEnd.

这篇关于Angular2 - 检索当前网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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