Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import { Component, OnInit } from '@angular/core';
  2. import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
  3. import 'rxjs/add/operator/filter';
  4.  
  5. @Component({
  6. selector: 'breadcrumb',
  7. template:`
  8. <span *ngFor="let breadcrumb of breadcrumbs">
  9. <a [routerLink]="breadcrumb.url">
  10. {{ breadcrumb.label }}
  11. </a>
  12. <span *ngIf="!last">></span>
  13. </span>`
  14. })
  15. export class BreadcrumbComponent implements OnInit {
  16. private breadcrumbs: Array<{}> = [];
  17.  
  18. constructor (
  19. private router:Router,
  20. private route:ActivatedRoute
  21. ) { }
  22.  
  23. ngOnInit() {
  24. const ROUTE_DATA_BREADCRUMB: string = 'breadcrumb';
  25. const PRIMARY_OUTLET: string = 'primary';
  26.  
  27. this.router.events
  28. .filter( event => event instanceof NavigationEnd)
  29. .subscribe( event => {
  30.  
  31. //reset breadcrumbs
  32. this.breadcrumbs = [];
  33.  
  34. //set the url to an empty string
  35. let url: string = "";
  36.  
  37. let currentRoute = this.route.root, url = '';
  38. let childrenRoutes = currentRoute.children;
  39. currentRoute = null;
  40.  
  41. childrenRoutes.forEach( route => {
  42.  
  43. // Verify this is the primary route
  44. if (route.outlet !== PRIMARY_OUTLET) {
  45. return;
  46. }
  47.  
  48. // Verify the custom data property "breadcrumb" is specified on the route
  49. if (!route.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
  50. return;
  51. }
  52.  
  53. //get the route's URL segment
  54. let routeURL: string = route.snapshot.url
  55. .map(segment => segment.path)
  56. .join('/');
  57.  
  58. // Fetch Primary outlet
  59. if (route.outlet === 'primary') {
  60. let routeSnapshot = route.snapshot;
  61.  
  62. console.log('Snapshot', routeSnapshot);
  63.  
  64. // Build segment path
  65. let url: string = routeSnapshot.url
  66. .map( segment => segment.path )
  67. .join('/');
  68.  
  69. //append route URL to URL
  70. url += `/${url}`;
  71.  
  72. console.log('Url segment', url);
  73.  
  74. //add breadcrumb
  75. this.breadcrumbs.push({
  76. label: route.snapshot.data[ROUTE_DATA_BREADCRUMB],
  77. url: url
  78. });
  79.  
  80. }
  81. });
  82.  
  83. })
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement