How to get current route custom data in angular 2?

后端 未结 11 1797
旧时难觅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 06:58

    This worked for me in app.component.ts (ng 5)

     constructor(
        private router: Router,
    ) {
    
     router.events.subscribe((routerEvent: Event) => {
           this.checkRouterEvent(routerEvent);
        });
    }
    
    checkRouterEvent(routerEvent: Event): void {
        if (routerEvent instanceof ActivationStart) {
            if (routerEvent.snapshot.data.custom_data) {
                this.currentpage = routerEvent.snapshot.data['custom_data'];
                console.log('4.' + this.currentpage);
            }
    
        }
    
    0 讨论(0)
  • 2020-12-05 07:02
      public constructor(private route:ActivatedRoute, private router:Router) {
          console.log(route.snapshot.data['title']);
      }
    
    0 讨论(0)
  • 2020-12-05 07:09

    asmmahmud's Answer works well till Angular 5.x but 6.X breaks the this.router.events since rxjs 6.x has breaking changes. So just came across an update:

    import {filter} from 'rxjs/operators';
    import {map, mergeMap} from 'rxjs/internal/operators';
    
    router.events
              .pipe(filter(event => event instanceof NavigationEnd),
                map(() => {
                  let route = activatedRoute.firstChild;
                  let child = route;
                  while (child) {
                    if (child.firstChild) {
                      child = child.firstChild;
                      route = child;
                    } else {
                      child = null;
                    }
                  }
                  return route;
                }),
                mergeMap(route => route.data)
              )
              .subscribe(data => {
                console.log(data);
              });
    
    0 讨论(0)
  • 2020-12-05 07:13

    After I tested various solution, the angular support group answer actually solved this problem nicely.

    ActivatedRoute doesn't carry data, and here's the solution for detecting the page variable within the data: { page: 'login' }.

    import { Router, RoutesRecognized } from '@angular/router';
    
    export class AppComponent {
      page = '';
      constructor(private router: Router) {
        // listen to page variable from router events
        router.events.subscribe(event => {
          if (event instanceof RoutesRecognized) {
            let route = event.state.root.firstChild;
            this.page = 'page-' + route.data.page || '';
            console.log('Page', this.page);
          }
        });
      }
    }
    
    0 讨论(0)
  • 2020-12-05 07:13

    After I tried a lot, I found the best solution

      private ngUnsubscribe$ = new Subject();
    
        constructor (private router: Router, private route: ActivatedRoute) { }
        
         ngOnInit () {
            const routeEndEvent$ = this.router.events
              .pipe(
                filter(e => e instanceof NavigationEnd),
                tap(() => console.warn("END")),
            );
        
            this.router.events
              .pipe(
                filter(e => e instanceof ChildActivationEnd && e.snapshot.component === this.route.component),
                buffer(routeEndEvent$),
                map(([ev]) => (ev as ChildActivationEnd).snapshot.firstChild.data),
                takeUntil(this.ngUnsubscribe$)
              )
              .subscribe(childRoute => {
                console.log('childRoute', childRoute);
              })
          }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题