0

I want to monitor routing events in an angular app and maybe change the past during certain conditions. I wrote the following class:

import {Event, RouterEvent, Router} from '@angular/router';
import {filter} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class RounterListenerService implements OnInit{

  constructor(private router: Router) {

  }

  ngOnInit() {

    this.router.events.pipe(
      filter((e: Event): e is RouterEvent => e instanceof RouterEvent)
    ).subscribe((e: RouterEvent) => {
      console.log("navigated");
    });
  }

}```

When I implement this, nothing happens when I navigate. I have checked and the whole class does not seem to be initiated. So I guess I need it to include it in the project somehow, but I do not know how? So any way I can get this to work?

  • try import NavigationEnd from '@angular/router'. It allows you to specifically handle navigation end events and then check if the event is an instance of NavigationEnd before logging the URL. – Ramziya Nisham May 23 '23 at 08:21
  • @VasimHayat not required as injectable root is already mentioned – super cool May 23 '23 at 08:27

1 Answers1

0

RouterListnerService

import { Injectable } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class RouterListnerService{

  constructor(private router: Router) { }

  initializeRouterEventsListener() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        // Navigation started
        console.log('Navigation started');
      }

      if (event instanceof NavigationEnd) {
        // Navigation ended successfully
        console.log('Navigation ended');
      }

      if (event instanceof NavigationError) {
        // Navigation error occurred
        console.log('Navigation error');
      }

      if (event instanceof NavigationCancel) {
        // Navigation canceled
        console.log('Navigation canceled');
      }
    });
  }
}

and your root app component injects the service and call the initializeRouterEventsListener method

import { Component, OnInit } from '@angular/core';
import { RouterEventsService } from './router-events.service';

@Component({
  selector: 'app-root',
  template: 'Your root component template',
  styleUrls: ['Your root component styles']
})
export class AppComponent implements OnInit {

  constructor(private routerEventsService: RouterEventsService) { }

  ngOnInit() {
    this.routerEventsService.initializeRouterEventsListener();
  }
}
Vasim Hayat
  • 909
  • 11
  • 16
  • This worked! Thank you! I man just used to everything in Angular this far boing more or less automatic, so did not considering initalizing it manually. – NorwegianDeveloper005 May 23 '23 at 08:40