- import { Component, OnInit } from '@angular/core';
- import { Router, NavigationEnd, RoutesRecognized } from '@angular/router';
- @Component({
- selector: 'my-app',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent implements OnInit {
- routerSub: any;
- data: any;
- constructor(
- private router: Router) {
- }
- ngOnInit() {
- this.routerSub = this.router.events.subscribe((evt) => {
- if (evt instanceof RoutesRecognized) {
- // some Angular clumsiness
- this.data = {};
- this.findStateData(evt.state.root.firstChild);
- }
- if (!(evt instanceof NavigationEnd)) {
- return;
- }
- window.scrollTo(0, 0);
- });
- }
- findStateData(firstChild: any){
- if(!firstChild){
- return;
- }
- if(firstChild.data){
- for(let key in firstChild.data){
- if (firstChild.data.hasOwnProperty(key)) {
- this.data[key] = firstChild.data[key];
- }
- }
- }
- this.findStateData(firstChild.firstChild);
- }
- ngOnDestroy(): void {
- this.routerSub.unsubscribe();
- }
- }