Angular 6 - Get current route and it's data

夙愿已清 提交于 2020-01-20 21:43:29

问题


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

say if this is the route structure:

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'}
      },
      ...
    ]
  },
  ...
]

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.?


回答1:


@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);
}
}



回答2:


  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;
  }

routing

{
  path: 'list',
  component: DialogListComponent,
  data: {
    headerClasses: 'col-lg-8',
  },
},



回答3:


You can access the route's data property from the snapshot like this:

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'];
  }

}


来源:https://stackoverflow.com/questions/50877410/angular-6-get-current-route-and-its-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!