Cannot get RouterEvent to work in Angular 12

350 views Asked by At

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?

1

There are 1 answers

1
Vasim Hayat On

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();
  }
}