Search code examples
angularangular-routerangular8

On refresh not getting `router events`


I am doing a breadcrumb for my project. I have two issues here:

  1. When I come from its sibling page, breadcrumb not generated
  2. When page refreshed the breadcrumb not generated

How to solve both of them?

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RoutesRecognized, NavigationStart,  NavigationEnd, Params, PRIMARY_OUTLET } from '@angular/router';
import { filter, map } from 'rxjs/operators';
import { BreadCrumbsService } from './../../services/bread-crumbs.service';


@Component({
    selector: 'bread-crumbs',
    templateUrl: './bread-crumbs.component.html',
    styleUrls: ['./bread-crumbs.component.scss']
})
export class BreadCrumbsComponent implements OnInit {

    breadcrumbList: Array<any> = [];

    /**
        * Setting Breadcrumb object, where name for display, path for url match,
        link for heref value, getting datas from BreadCrumbsService service
    */

    constructor(private router: Router, private bCService: BreadCrumbsService) {

        this.generateBreadCrumb();

    }

    ngOnInit() {}

    generateBreadCrumb() {

        console.log('hi');

        let routerUrl: string, routerList: Array<any>, target: any;

        this.router.events.subscribe((router: any) => {

            console.log('do'); //not consoles on above 2 points

            routerUrl = router.urlAfterRedirects;


        });

    }

}

Solution

  • The Router subscription-logic i´m using is even more restrictive and works:

    constructor(private router: Router) { 
         router.events.subscribe(event => {
                if (event instanceof NavigationEnd) {
                    console.log(event.urlAfterRedirects);
                }
              });
    }

    So i think your issue is caused by the way you set up your router module. Did you test wether your router works by using two components in two URLS? Or would you share your router module with us?