Angular 6 - Get current route and it's data

前端 未结 3 1871
离开以前
离开以前 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: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',
      },
    },
    

提交回复
热议问题