使用Angular2,我如何检索当前激活的组件和路径?
例如,我可能有以下路由:
{ path: '', component: HomeComponent },
{ path: 'list', component: ListComponent },
{ path: ':id/', component: CustomComponent }如果我已经导航到https://domain.com/test,有没有办法知道我当前正在查看CustomComponent并检索id/路径,在本例中是“测试”?
我可以使用带正则表达式的window.location.pathname来获取路径,但是这很混乱,而且仍然不允许我轻松地获取活动组件。
发布于 2018-08-14 12:16:35
在ActivatedRouteSnapshot中,component属性被定义为以下属性之一
component: Type<any> | string | null;因此,除非您已经确保拥有Type<any>,否则不能只执行component.name。这是因为字符串上的.name不存在。
现在,Type<any>实际上是一个创建类型(组件类型)的函数,其定义如下:
export interface Type<T> extends Function {
new (...args: any[]): T;
}所以你可以做一些类似这样的事情,它将实际编译
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;
}一种“优雅”的方式是使用typescript typeguard (尽管坦率地说,在这种情况下它并没有给你带来比我刚才所说的更多的好处)。
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在构建中仍然有效,但不幸的是,在使用r时,它将最终成为随机的东西。
我不得不注入private element: ElementRef<HTMLElement>,然后查找标记名。这将仍然存在,即使使用AOT prod build。这样做可能会有性能成本,所以如果您经常使用它,请对其进行缓存。
if (element.nativeElement.tagName.startsWith('RR-')){
super.name = element.nativeElement.tagName;
}https://stackoverflow.com/questions/41580495
复制相似问题