Angular 6 - 获取当前路线及其数据 [英] Angular 6 - Get current route and it's data

查看:37
本文介绍了Angular 6 - 获取当前路线及其数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取当前路径并获取其数据、子项和父项?

How do you able to get current route you're in and get's it's data, children and it's parent?

说这是否是路由结构:

const routes: Routes = [
  {path: 'home', component: HomeComponent, data: {title: 'Home'}},
  {
    path: 'about', 
    component: AboutComponent, 
    data: {title: 'About'},
    children: [
      {
        path: 'company',
        component: 'CompanyComponent',
        data: {title: 'Company'}
      },
      {
        path: 'mission',
        component: 'MissionComponent',
        data: {title: 'Mission'}
      },
      ...
    ]
  },
  ...
]

如果我目前在 CompanyComponent,我如何获得我当前的路径 w/c 是 Company,让它的父 w/c 是 about,它是 数据和它的兄弟姐妹如任务等?

If I am currently in CompanyComponent, how do I get my current route w/c is Company, get it's parent w/c is about, it's data and it's siblings such as mission, etc.?

推荐答案

@Component({...})
export class CompanyComponent implements OnInit {

constructor(
  private router: Router,
  private route: ActivatedRoute
) {}

ngOnInit() {

  // Parent:  about 
  this.route.parent.url.subscribe(url => console.log(url[0].path));

  // Current Path:  company 
  this.route.url.subscribe(url => console.log(url[0].path));

  // Data:  { title: 'Company' } 
  this.route.data.subscribe(data => console.log(data));

  // Siblings
  console.log(this.router.config);
}
}

这篇关于Angular 6 - 获取当前路线及其数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆