15

如何获取您所在的当前路线及其数据、子项和父项?

如果这是路由结构:

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 is Company,获取其父 w/c is about、其数据及其兄弟姐妹(例如任务等)?

4

3 回答 3

19
@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);
}
}
于 2018-07-31T21:42:15.837 回答
3
  constructor(
    private router: Router,
    private route: ActivatedRoute,
  ) {
  }

  ngOnInit() {
    this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
        map(() => {
          return this.getHeaderClasses();
        }),
      )
      .subscribe((headerClasses: string | null) => {
        this.headerClasses = headerClasses;
      });
    this.headerClasses = this.getHeaderClasses();
  }


  getHeaderClasses(): string | null {
    let child = this.route.firstChild;
    while (child) {
      if (child.firstChild) {
        child = child.firstChild;
      } else if (child.snapshot.data && child.snapshot.data['headerClasses']) {
        return child.snapshot.data['headerClasses'];
      } else {
        return null;
      }
    }
    return null;
  }

路由

{
  path: 'list',
  component: DialogListComponent,
  data: {
    headerClasses: 'col-lg-8',
  },
},
于 2019-03-11T11:14:47.710 回答
2

您可以像这样从快照中访问路由的数据属性:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
    templateUrl: './app/home/welcome.component.html'
})
export class WelcomeComponent implements OnInit {
    public pageTitle: string;

    constructor( private route: ActivatedRoute) {
    } 

    ngOnInit(): void {
     this.pageTitle = this.route.snapshot.data['title'];
  }

}
于 2019-08-23T10:51:38.150 回答