首页 > 解决方案 > Angular If 语句 - 检查路线

问题描述

我想为我的程序做一个 if 语句来检查我当前在哪个路由/路径上。

我有一个函数,这个函数应该只在我在特定路径上时才起作用。例如:如果路径是主页我在“主页”上,但是如果我在 url 中写“主页/添加”,我想调用一个函数。我试过“ if(this.router.url.include('add') { .... code ... } 但它没有用。有人可以帮我吗?谢谢!

标签: angulartypescriptpathroutes

解决方案


You have to add nested route '/add' and then in this component which will be available for 'add' route - call your function on ngOnInit(){ /// }.

const routes: Routes = [
  {
    path: 'homepage',
    component: DashboardComponent,
    children: [
      {path: 'add', component: DashboardAddComponent}
    ]
  }
]

then in component:

class DashboardAddComponent implements OnInit {
  ngOnInit() {
    // ... CALL HERE
  }
}

推荐阅读