检索活动组件和路径 [英] Retrieving the active component and path
问题描述
使用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.
推荐答案
在ActivatedRouteSnapshot
中,component
属性被定义为以下项之一
In ActivatedRouteSnapshot
the component
property is defined as being one of the following
component: Type<any> | string | null;
因此,除非您已经确定拥有Type<any>
,否则不能只做component.name
.这是因为字符串上的.name
不存在.
So you can't just do component.name
unless you've already made sure you have Type<any>
. This is because .name
on a string doesn't exist.
现在Type<any>
实际上是一个创建类型(您的组件类型)的函数,并定义为:
Now Type<any>
is actually a function that creates the type (your component type) and is defined as:
export interface Type<T> extends Function {
new (...args: any[]): T;
}
因此,您可以执行以下操作,该操作实际上会编译
So you can do something like this, which will actually compile
if (typeof(this.route.snapshot.component) === 'function')
{
// the compiler is 'smart' enough to know that component here must be Type<T>
const name = this.route.snapshot.component.name;
}
一种优雅"的方法是使用打字稿字体保护程序(尽管坦率地说,它并没有给我带来太多好处).
An 'elegant' way to do it is using a typescript typeguard (although to be frank in this case it doesn't give you much of a benefit over what I just said).
isComponent(item: Type<any> | string | null): item is Type<any>
{
return typeof item === 'function';
}
然后您可以说this.name = isComponent(this.route.snapshot.component) ? this.route.snapshot.component : null
.
重要:
component.name
在AOT版本中仍然有效,但不幸的是,对于--prod
来说,它最终会变成r
之类的随机变量.
Important:
component.name
is still valid in an AOT build, but unfortunately with --prod
it will end up being something random like r
.
我不得不注入private element: ElementRef<HTMLElement>
,然后寻找标签名称.即使使用AOT生产的产品,它仍然会存在.这样做可能会降低性能,因此如果您经常使用它,请对其进行缓存.
I've resorted to having to inject private element: ElementRef<HTMLElement>
and then look for the tag name. This will still be present even with an AOT prod build. There may be a performance cost to doing this so cache it if you're using it a lot.
if (element.nativeElement.tagName.startsWith('RR-')){
super.name = element.nativeElement.tagName;
}
这篇关于检索活动组件和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!