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

The attribute is not found on the combined type

After combing through various questions on stackoverflow, I couldn't find a solution to my specific case. This is the scenario: interface FruitBox { name: string desc: { 'orange': number; 'banana': number; } } interf ...

The 'connectedCallback' property is not found in the 'HTMLElement' type

After taking a break from my project for a year, I came back to find that certain code which used to work is now causing issues: interface HTMLElement { attributeChangedCallback(attributeName: string, oldValue: string, newValue: string): void; con ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

Having trouble centering an icon in a cell within AG Grid?

I am struggling with aligning my checkmarks within the cells of my AG Grid. Currently, they are all left aligned but I need them to be centered. Adjusting the alignment for text is not an issue, but I can't seem to center the material icons. It appear ...

Create a single declaration in which you can assign values to multiple const variables

As a newcomer to react/JS, I have a question that may seem basic: I need multiple variables that are determined by a system variable. These variables should remain constant for each instance. Currently, my approach is functional but it feels incorrect to ...

Adjust the height of a div vertically in Angular 2+

Recently, I started using angular2 and I've been attempting to create a vertically resizable div without success. I have experimented with a directive for this purpose. Below is the code for my directive: import { Directive, HostListener, ElementRef ...

Error: Unable to access the 'next' property of null within an Angular 2 Observable

Issue Found An error of type TypeError has occurred: Cannot read property 'next' of null Problematic Template Utilizing Observer.next import { NavService } from '../../providers/services/nav-service/nav-service'; @Component({ ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

Is it feasible to alter the TypeScript interface for the default JavaScript object (JSON)?

When dealing with cyclic objects, JSON.stringify() can break (as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value) An alternative solution suggested in the same article is to use 'cycle.js&apos ...

The cell must be crafted with a styling attribute to determine its placement

While working on my web app using React, I encountered a console warning: react_devtools_backend.js:4012 Rendered cell should include style property for positioning. at Grid2 (http://localhost:5173/node_modules/.vite/deps/react-virtualized.js?v=b41cc5 ...

Updating the value of an input field in Angular 2

When I enter 123 in my input field and submit, I want to see 456. Is there a way to change the value of an input programmatically? Here is my HTML code using Ionic2: <ion-textarea [ngFormControl]="message"></ion-textarea> This is the JavaSc ...

Using class-validator in Node.js to validate arrays of objects

My goal is to verify the Alcohol ID and Alcohol Name for emptiness. Below is the format I am working with: { "barId": "string", "barName": "string", "drinksItems": [ { "alcoholId": "string", "alcoholName": "string", "mixerLis ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

Utilizing import for Ionic3 to export const with logic

While developing an app using ionic3, I encountered an issue with setting up a proxy. When running in a browser, Ionic was able to recognize the path of my proxyUrl as shown below. ionic.config.json { "name": "myApp", "app_id": "", "v2": true, "t ...

Verifying User Permissions with Angular 2/4 and API

I am currently in the process of developing an Angular 2/4 application that interacts with an API built in Laravel 5.4. One area I'm seeking guidance on involves checking authentication and permissions on the backend through Angular. I want to verify ...

Ways to dynamically generate a generic that expands a union class type

Reviewing the code snippet: const events = { a: ['event1' as const, 'event2' as const], b: ['event3' as const, 'event4' as const], }; class SomeClass< T extends AnotherClass<typeof events[keyof typeof ev ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

Getting the logged in user's ID in Angular using MongoDB and Node.js for the backend

How can I retrieve the logged user's ID so that when they click on "My profile", they are directed to url/profile/theirId? Thank you for your help! Below is my authentication.service code: export interface UserDetails{ username: string email: stri ...