Angular 6 - Get current route and it's data

前端 未结 3 1857
离开以前
离开以前 2020-12-29 09:09

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:

相关标签:
3条回答
  • 2020-12-29 09:44

    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'];
      }
    
    }
    
    0 讨论(0)
  • 2020-12-29 09:54
      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',
      },
    },
    
    0 讨论(0)
  • 2020-12-29 09:56
    @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);
    }
    }
    
    0 讨论(0)
提交回复
热议问题