1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Implementing a breadcrumb system using routing history in Angular 18

Discussão em 'Angular' iniciado por Nadee Darshika, Setembro 10, 2024.

  1. I am currently implementing a breadcrumb system using routing history. The issue arises when the current path is the root. For example, I have set the root path to load a user table view. When a user is clicked, it navigates to the user add/edit page. On the user add/edit page, the breadcrumb should display as "User > User Add/Edit," but it only shows "User Add/Edit."

    I can't simply check if the current URL contains the root as a subset and append "User" because every path contains the root as a subset. How should I handle this situation and implement the breadcrumb correctly?

    import { Injectable } from '@angular/core';
    import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
    import { filter } from 'rxjs/operators';
    import { BehaviorSubject } from 'rxjs';

    interface RouteHistory {
    url: string;
    breadcrumb: string | null;
    }

    @Injectable({
    providedIn: 'root'
    })
    export class RoutingHistoryService {
    private history: RouteHistory[] = [];
    private historySubject = new BehaviorSubject<RouteHistory[]>(this.history);

    constructor(private router: Router, private route: ActivatedRoute) {
    this.router.events.pipe(
    filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
    this.addBreadcrumbHistory();
    });
    }

    private addBreadcrumbHistory() {
    let url = '';
    let currentRoute = this.route.root;
    let breadcrumbLabel: string | null = null;

    while (currentRoute.children.length > 0) {
    const childRoutes = currentRoute.children;
    currentRoute = childRoutes[0];
    const routeURL: string = currentRoute.snapshot.url.map(segment => segment.path).join('/');
    url = `${url}/${routeURL}`.replace(/\/$/, '');

    if (currentRoute.snapshot.data['breadcrumb']) {
    breadcrumbLabel = currentRoute.snapshot.data['breadcrumb'];
    }
    }

    if (!url || url === '/') {
    this.history.push({
    url: '/',
    breadcrumb: 'Users' // In order to set the breadcrumb for the root
    });
    }else{
    this.history.push({
    url,
    breadcrumb: breadcrumbLabel
    });
    }

    this.historySubject.next(this.history);
    }

    getHistory() {
    return this.historySubject.asObservable();
    }

    getBreadcrumbForUrl(url: string): string | null {
    const historyEntry = this.history.find(entry => entry.url === url);
    return historyEntry ? historyEntry.breadcrumb : null;
    }

    clearHistory() {
    this.history = [];
    this.historySubject.next(this.history);
    }
    }


    also here is the breadcrumb component.ts

    import {Component, OnDestroy, OnInit} from '@angular/core';
    import {Subscription} from 'rxjs';
    import {RoutingHistoryService} from "../../../service/routing.history.service";

    @Component({
    selector: 'app-breadcrumb',
    templateUrl: './breadcrumb.component.html',
    styleUrl: './breadcrumb.component.scss'
    })

    export class BreadcrumbComponent implements OnInit, OnDestroy {
    history: Array<{ url: string, breadcrumb: string | null }> = [];
    breadcrumbTrail: any[] = [];
    private historySubscription: Subscription;

    constructor(private routingHistoryService: RoutingHistoryService) {
    }

    ngOnInit() {
    this.historySubscription = this.routingHistoryService.getHistory().subscribe(updatedHistory => {
    this.history = updatedHistory;
    this.updateBreadcrumbTrail();
    });
    }

    private updateBreadcrumbTrail() {
    const currentUrl = this.history.length > 0 ? this.history[this.history.length - 1].url : '';
    const urlSegments = currentUrl.split('/').filter(segment => segment);

    this.breadcrumbTrail = [];
    let urlAccumulator = '';

    if(currentUrl === '' || currentUrl === '/'){
    this.breadcrumbTrail.push({
    label: 'Users',
    routerLink: '/'
    });
    }

    urlSegments.forEach((segment, index) => {
    urlAccumulator = `${urlAccumulator}/${segment}`;
    const breadcrumbLabel = this.routingHistoryService.getBreadcrumbForUrl(urlAccumulator);
    this.breadcrumbTrail.push({
    label: breadcrumbLabel,
    routerLink: index < urlSegments.length - 1 ? urlAccumulator : null
    });
    });
    }

    ngOnDestroy() {
    if (this.historySubscription) {
    this.historySubscription.unsubscribe();
    }
    }
    }


    How should i solve this?

    I have set the breadcrumb label for the root path as well, but it is not being applied.

    Continue reading...

Compartilhe esta Página