Saltar al contenido

Migas de pan dinámicas de Angular 2

Por fin después de tanto batallar ya encontramos la contestación de este atasco que muchos lectores de este sitio han presentado. Si deseas compartir algún dato no dejes de dejar tu conocimiento.

Solución:

Espero que no sea demasiado tarde para responder esta pregunta :D, así que aquí hay un ejemplo funcional de CodeSandbox con dos implementaciones de migas de pan, que usa el routerdata Opción para pasar y recopilar datos para la ruta de navegación.

Explicación del código:

Mire los comentarios dentro del componente de ruta de navegación.

Aquí está el componente de migas de pan

import  Component, OnInit  from "@angular/core";
import 
  Router,
  Event,
  ActivationStart,
  ActivatedRouteSnapshot,
  ActivationEnd,
  NavigationEnd,
  NavigationStart
 from "@angular/router";
import  filter, map, buffer, pluck  from "rxjs/operators";

/**
 * Check if an angular router 'Event' is instance of 'NavigationEnd' event
 */
const isNavigationEnd = (ev: Event) => ev instanceof NavigationEnd;
/**
 * Check if an angular router 'Event' is instance of 'NavigationEnd' event
 */
const isActivationEnd = (ev: Event) => ev instanceof ActivationEnd;

@Component(
  selector: "app-breadcrumb",
  templateUrl: "./breadcrumb.component.html",
  styleUrls: ["./breadcrumb.component.scss"]
)
export class BreadcrumbComponent implements OnInit 
  bcLoadedData;
  bcForDisplay;

  constructor(private router: Router) 

  ngOnInit() 
    /**
     * navigationEnd$ is trigered once per completed routing event, in other words
     * once per loading a component that is in the end of the current route
     */
    const navigationEnd$ = this.router.events.pipe(filter(isNavigationEnd));

    /**
     * Here we subscribe to all navigation events, in order to update
     * our route "data", which we will use for the breadcrumb visualization.
     *
     * Than we filter the events emitted from the `router` in such way, that we are only
     * taking action upon a completed router event (in other words we are subscribing only for `ActivationEnd`
     * events)
     *
     * We use pluck to get only the requried bredcrumb data
     *
     * The buffer operator accumulates all `data` coming from the router and emmits the accumulated data once
     * when a `NavigationEnd` event passes troufh `navigationEnd$`
     *
     * The `map` in the end is used to reverse the collected data, in order to convert it to more logical
     * sequence. Without the revers first we will get the data for the current route, after that for it's parent
     * and so on (that is how the ng router works).
     */
    this.router.events
      .pipe(
        filter(isActivationEnd),
        pluck("snapshot"),
        pluck("data"),
        buffer(navigationEnd$),
        map((bcData: any[]) => bcData.reverse())
      )
      .subscribe(x => 
        this.bcLoadedData = x;
      );
  

.breadcrumb 
    display: flex;

    &.simple 
        border: 2px solid blueviolet;
        border-radius: 4px;
    

    .breadcrumb-separator 
        margin: 10px;
    


Aquí está la estructura de las rutas.

const routes: Routes = [
	 path: '', pathMatch: 'full', component: MockComponentComponent, data:  bc: 'Looking outside'  ,
	
		path: 'home', component: MockComponentComponent,
		data:  bc: 'I see a home' ,
		children: [
			
				path: 'primaryHouse', component: MockComponentComponent,
				data:  bc: 'I'm going inside the home' ,
				children: [
					
						path: 'kitchen', component: MockComponentComponent,
						data:  bc: 'look inside the kitchen' 
					,
					
						path: 'bedroom', component: MockComponentComponent,
						data:  bc: 'look inside the bedroom' 
					
				]
			,
			
				path: 'guestHouse', component: MockComponentComponent,
				data:  bc: 'I'm going in the back yard' 
			
		]
	
];

Comentarios y puntuaciones

Acuérdate de que puedes optar por la opción de comentar tu experiencia si te ayudó.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *