1. import { Component, OnInit } from '@angular/core';
  2. import { Router, NavigationEnd, RoutesRecognized } from '@angular/router';
  3. @Component({
  4. selector: 'my-app',
  5. templateUrl: './app.component.html',
  6. styleUrls: ['./app.component.css']
  7. })
  8. export class AppComponent implements OnInit {
  9. routerSub: any;
  10. data: any;
  11. constructor(
  12. private router: Router) {
  13. }
  14. ngOnInit() {
  15. this.routerSub = this.router.events.subscribe((evt) => {
  16. if (evt instanceof RoutesRecognized) {
  17. // some Angular clumsiness
  18. this.data = {};
  19. this.findStateData(evt.state.root.firstChild);
  20. }
  21. if (!(evt instanceof NavigationEnd)) {
  22. return;
  23. }
  24. window.scrollTo(0, 0);
  25. });
  26. }
  27. findStateData(firstChild: any){
  28. if(!firstChild){
  29. return;
  30. }
  31. if(firstChild.data){
  32. for(let key in firstChild.data){
  33. if (firstChild.data.hasOwnProperty(key)) {
  34. this.data[key] = firstChild.data[key];
  35. }
  36. }
  37. }
  38. this.findStateData(firstChild.firstChild);
  39. }
  40. ngOnDestroy(): void {
  41. this.routerSub.unsubscribe();
  42. }
  43. }