Angular: updating a single route triggers multiple 'NavigationEnd' events

I am currently working with Angular 4 and have written the following code in one of my components to detect when a route has changed and reload the page:

ngOnInit() {
        this.router.events.subscribe((value) => {
          if (value instanceof NavigationEnd) {
             console.log(value);
          }
        });
    }

However, I am encountering an issue where multiple 'NavigationEnd' events are triggered for a single route change. In some cases, the console logs up to 6 or 7 values.

Why is this happening?

Answer №1

When you mention "reload page," I assume you are referring to triggering the navigate method within this.router. If this is the case, the issue may be linked to the creation of a new observer for router events every time an instance of this component is created without properly disposing of the generated subscription during the ngOnDestroy cycle. To address this issue, consider the following approach:

import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';    

export class BarComponent implements OnInit, OnDestroy {
   private _routerSub = Subscription.EMPTY;
   constructor(private router: Router){}

   ngOnInit(){
     this._routerSub = this.router.events
         .filter(event => event instanceof NavigationEnd)
         .do(event => console.log(value)) // use do operator for log operations
         .subscribe((value) => {
          //perform actions with the value
         });
   }

   ngOnDestroy(){
     this._routerSub.unsubscribe();
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The Angular build encountered an error stating that the 'AggregateQuerySnapshot<T>' generic type requires one type argument after running npm install

Recently, I encountered a new error in my Angular project after performing an npm upgrade for maintenance purposes. Strangely, the upgrade did not involve changing any direct dependency versions. The problem arises when trying to run 'ng serve,' ...

Integrate a fresh global JSX attribute into your React project without the need for @types in node_modules

It is crucial not to mention anything in tsconfig.json. Error Type '{ test: string; }' cannot be assigned to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'test' does not exi ...

An automatic conversion cannot handle spaces and prohibited characters in Object keys

The AlphaVantage API uses spaces and periods in the keys. Their API documentation is not formal, but you can find it in their demo URL. In my Typescript application, I have created data structures for this purpose (feel free to use them once we solve the ...

Encountering build errors with @angular/cdk and @angular/forms post updating to Angular 11

Upon upgrading to Angular 11, I encountered a series of errors during the build process of my solution: \node_modules\@angular\cdk\coercion\array.d.ts(10,60): error TS1005: Build:',' expected. \node_modules\@ang ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

I am facing a problem with React Hooks useRef where I am unable to retrieve the updated state value

Trying to use useRef with React hooks, I encountered an issue where the state of the child component changes when calling the setAccountVal method, but upon alerting the value it remains as "Ege". Any ideas on how to resolve this? import React, { useS ...

Incorporating D3's library functions into Rxjs for seamless integration with Observables

I'm really struggling with this concept and could use some guidance. My goal is to monitor when data is fetched, but I seem to have confused the process. Here's what I've tried so far: Using d3.tsv for an ajax request. var test = Rx.Observa ...

Tips for creating an initial angular2 application with jspm integration using angular cli

ng new MY_PROJECT cd MY_PROJECT ng serve I'm curious if there is a way to generate the starter project using systemjs/jspm instead of webpack with Angular. If not, could you please provide detailed steps on how to do this? ...

Exploring File Read and Write Functionality in Angular 4

I want to develop an offline Task List in Angular 4. However, I am facing difficulty in finding a method to save data in a file on the client side using JavaScript or Angular. My current approach involves using browser's localStorage, but it is slow ...

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

Angular routerlink params can be secured using encryption and decryption techniques

Can anyone provide me with a reliable method to encrypt and decrypt querystring parameters, such as gmail.com? Also, I am looking for information on how to obtain these query parameters. The path structure I am working with is: { path: 'myPrograms/: ...

During the installation of Angular CLI, an error occurred indicating an unexpected ending of JSON input while parsing near the string '...gsJjnNLbV xrOnxOWiCk'

C:\Users\BB>node --version v14.15.0 C:\Users\BB>npm --version 8.3.2 npm install -g @react/react-native npm ERR! Error: Unable to find module '@react/react-native' npm ERR! A detailed log of this process can be locate ...

"Hmm, the React context's state doesn't seem to be changing

I have been working on a next.js app and I encountered an issue related to using react context to export a state. Despite my efforts, the state doesn't seem to update and it remains stuck at the initial value defined by the createContext hook, which i ...

What is the reason for instances being compatible even if their class constructors do not match?

Why are the constructors in the example below not compatible, but their instances are? class Individual { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } class Worker { name: st ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

The method of pausing a function until the result of another function is returned

There is a function named 'updateProfile()' that includes a condition, which checks for the value of variable 'emailChangeConfirm' obtained from another function called 'updateEmailAllProcessing()'. The issue lies in the fact ...

The environment production variable is perpetually set to true within the app.module.ts file

I'm currently facing an issue with setting a configuration in my app.module file that should differ based on whether I'm in production or not. Within my environment.ts file, I have the following: export const environment = { production: false ...

Is it more efficient to wait for the server to respond, or should I update the client immediately

Today, I found myself contemplating an interesting question. As I work on developing a Single Page Application (SPA) using Angular, I am focusing on creating a calendar module similar to Google Calendar. This module will allow users to add, edit, and remov ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...