在子组件中显示面包屑

时间:2019-11-07 14:41:26

标签: angular angular-ui-router breadcrumbs

我在应用程序组件中有<app-breadcrumbs></app-breadcrumbs>。但是设计师决定在matcard中显示面包屑。

我尝试将<app-breadcrumbs></app-breadcrumbs>移到需要面包屑但不能正常工作的部分。.因为我没有孩子。在这种情况下我该怎么办。

get node() {

    return this.activatedRoute.snapshot.children[0].url[1] && this.activatedRoute.snapshot.children[0].url[1].path === 'my-account' ?
      this.activatedRoute.snapshot.children[0].firstChild.firstChild : this.activatedRoute.snapshot.children[0];
  }

  ngOnInit(): void {
    this.load(this.breadcrumbsFromRoute(this.node));
    this.__subjectSub = this.appSettings.currentBreadcrumb$.subscribe(breadcrumbs => {
      this.load(breadcrumbs);
    });
    this.__routeSub = this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
      this.load(this.breadcrumbsFromRoute(this.node));
    });
  }

  load(breadcrumbs: any[]) {
   if (breadcrumbs && breadcrumbs.length) {
     if (!breadcrumbs[0]['name']) {
       this.breadcrumbs = [];
       this.pageTitle = '';
       return;
     }
      this.breadcrumbs = breadcrumbs;
      this.pageTitle = '';
      this.breadcrumbs.forEach(breadcrumb => {
        if (breadcrumb.name) {
          this.pageTitle += ' > ' + breadcrumb.name;
        }
      });
      this.currentBreadcrumb = this.breadcrumbs[this.breadcrumbs.length - 1];
      if (!this.title.getTitle()) {
        this.title.setTitle(this.settings.name + this.pageTitle);
      }
    }
  }

  closeSubMenus() {
    if (window.innerWidth < 960) {
      this.sidenavMenuService.closeAllSubMenus();
    }
  }

  breadcrumbsFromRoute(node: ActivatedRouteSnapshot): Array<any> {
    const breadcrumbs = [];
    if (node.data['breadcrumb'] !== undefined) {
      if (node.url.length) {
        let urlSegments: UrlSegment[] = [];
        node.pathFromRoot.forEach(routerState => {
          urlSegments = urlSegments.concat(routerState.url);
        });
        const url = urlSegments.map(urlSegment => {
          return urlSegment.path;
        }).join('/');
        if (node.params.name) {
          breadcrumbs.push({
            name: node.params.name,
            url: '/' + url
          });
        } else {
          breadcrumbs.push({
            name: node.data['breadcrumb'],
            url: '/' + url
          });
        }
      }
    }
    return breadcrumbs;
  }

它在应用程序组件上运行完美,但在子组件中却出现此错误

Cannot read property 'url' of undefined

0 个答案:

没有答案