How to get current route custom data in angular 2?

后端 未结 11 1850
旧时难觅i
旧时难觅i 2020-12-05 06:21

I have set up routes is like below

const appRoutes: Routes = [
  {
    path: \'login\',
    component: LoginComponent,
    data: {
      title: \'Login TTX\         


        
11条回答
  •  佛祖请我去吃肉
    2020-12-05 07:15

    its work for component that not navigate (like header) :

    this.route.root.firstChild.snapshot.data['title']
    

    and complete example:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
    
    
    export class HeaderComponent implements OnInit {
      title: string;
    
      constructor(private route: ActivatedRoute, private router: Router ) { }
    
      ngOnInit() {
        this.router.events.subscribe(event => {
          if(event instanceof NavigationEnd) {
            this.title = this.route.root.firstChild.snapshot.data['title']
          }
        });
      }    
    }
    

    cerdit to this answare

提交回复
热议问题