检索活动组件和路径 [英] Retrieving the active component and path

查看:23
本文介绍了检索活动组件和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Angular2,我将如何检索当前活动组件和路径?

With Angular2, how would I retrieve the current active component and path?

例如我可能有以下路线:

For example I might have the following routes:

{ path: '', component: HomeComponent },
{ path: 'list', component: ListComponent },
{ path: ':id/', component: CustomComponent }

如果我导航到 https://domain.com/test 有没有办法知道我当前正在查看 CustomComponent 并检索 id/路径,在这种情况下是测试"?

If I had navigated to https://domain.com/test is there a way to know I'm currently viewing the CustomComponent and to retrieve the id/path, which in this case is "test"?

我可以使用带有正则表达式的 window.location.pathname 来获取路径,但这很混乱,并且仍然无法让我轻松获取活动组件.

I could use window.location.pathname with regex to get the path but this is messy and still doesn't allow me to easily get the active component.

推荐答案

是的,您可以使用路由器快照检查当前活动的组件-

Yes you can check current active component using router snapshot-

import { Router,ActivatedRoute }      from '@angular/router';

constructor(public route : ActivatedRoute) {
    var snapshot = route.snapshot;
    console.log(snapshot._routeConfig.component.name); //This will give you the name of current active component
  }

注意- snapshot._routeConfig.component.name 它将为您提供活动组件的名称,如果您想要 url,您也可以通过 .url 而不是名称来获取它

Note- snapshot._routeConfig.component.name it will give you the active component name, and if you want url you can also get it by .url instead of name

这篇关于检索活动组件和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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