如何从Angular 7中的当前URL获取路由名称

时间:2019-12-07 17:41:48

标签: angular angular-routing

当我开始对其进行路由时,我在路由中具有多个组件,但可以正常工作,但我有一些条件可以实现,这是他们从url获取路由名称的一种方法 这是我的路线

const routes: Routes = [
{path:'',redirectTo:'home',pathMatch:'full'},
{path:'home',component:HomeComponent},
{path:'about',component:AboutComponent},
{path:'portfolio',component:PorfolioComponent},
{path:'blog',component:BlogComponent},
{path:'contact',component:ContactComponent},
{path:'web-development',component:WebDelopementComponent},
{path:'software-app',component:SoftwareAppComponent},
{path:'graphic-designing',component:GraphicDesigningComponent},
{path:'e-business',component:ECommerceComponent},
{path:'single-blog/:id',component:SingleBlogComponent},
{path:'service-detail/:id',component:ServiceDetailComponent},
{path:'**',redirectTo:'home',pathMatch:'full'},
];

例如,这是我的网址

 http://localhost:4200/home or http://localhost:4200/about

我想从这个URL回家或大约要回家,所以我该如何在角度7中做到这一点

2 个答案:

答案 0 :(得分:4)

这是代码:

     constructor(private _router: Router,private activatedRoute:ActivatedRoute) {
           console.log(activatedRoute.snapshot.url); // array of states
           console.log(activatedRoute.snapshot.url[0].path);
           //this will give the path name
     }

答案 1 :(得分:1)

在角度路由器上下文之外的路径也许会有用,但在您的情况下,最好使用ActivatedRoute或Router

import { Location } from '@angular/common';


constructor(private location: Location) {
  console.log(location.path());
}