Joe*_*ani 6 typescript angular2-routing angular
使用 Angular2,我将如何检索当前活动组件和路径?
例如,我可能有以下路线:
{ path: '', component: HomeComponent },
{ path: 'list', component: ListComponent },
{ path: ':id/', component: CustomComponent }
Run Code Online (Sandbox Code Playgroud)
如果我导航到https://domain.com/test有没有办法知道我当前正在查看CustomComponent并检索 ID/路径,在这种情况下是“测试”?
我可以使用window.location.pathname正则表达式来获取路径,但这很混乱,并且仍然不允许我轻松获取活动组件。
小智 5
是的,您可以使用路由器快照检查当前活动组件 -
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
}
Run Code Online (Sandbox Code Playgroud)
注意- snapshot._routeConfig.component.name它将为您提供活动组件名称,如果您想要 url,您也可以通过 .url 而不是名称来获取它
是的,Angular 2 入门指南涵盖了所有这些,基本上你需要在组件上注入 ActivatedRoute,然后你可以通过订阅路由参数来检索你想要的信息。
我真的会推荐你做英雄的角度教程之旅,这实际上是他们提供的非常好的学习材料。
在组件构造函数中注入 ActivatedRoute:
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(params => {
console.log(params['id']);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13457 次 |
| 最近记录: |