Repetitive execution of Angular service function upon route change

In my Angular 8 project, there is a service function responsible for copying data. However, I encountered an issue where if I copy the data on a page, navigate to another page, and then return to the original page to copy the data again, it ends up duplicating the copied data. This duplication continues and the service function gets called multiple times, resulting in excessive copies being made.

Despite trying various methods, I have not been able to resolve this issue of data being copied multiple times. I hope you can comprehend my problem and provide some answers or solutions.

Below is the code from my app.module.ts file:

// App module imports
import { APP_BASE_HREF } from '@angular/common';
import { NgModule } from '@angular/core';
import { ModuleWithProviders } from '@angular/compiler/src/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';

// Component imports
import { AppComponent } from './app';
import { CategoryComponent } from './views/category';

// Service import
import { CategoryService } from './services/category';

@NgModule({
    declarations: [
        AppComponent,
        CategoryComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        ReactiveFormsModule.withConfig({ warnOnNgModelWithFormControl: 'never' }),
        HttpClientModule
    ],
    providers: [{ provide: APP_BASE_HREF, useValue: '/AngularProject/' }, CategoryService ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Here are the codes from my service file:

// Service implementation
import { Injectable } from "@angular/core";
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ICategory } from '../models/ICategory';

@Injectable({ providedIn: 'root' })
export class CategoryService {
    private linkIndex: string = "Ajax/Category/Index";
    private linkCopy: string = "Ajax/Category/Copy";

        constructor(private http: HttpClient) {
    }

    getIndex(): Observable<Array<ICategory>> {
        return this.http.get<Array<ICategory>>(this.linkIndex);
    }

    getCopy(id: string): Observable<boolean> {
        let params = new HttpParams().set("id", id);
        return this.http.get<boolean>(this.linkCopy, { params: params });
    }
}

Lastly, here's the code snippet from my CategoryComponent:

// Component logic
import { Component, OnDestroy, OnInit } from "@angular/core";
import { Subscription } from "rxjs";
import { Router } from "@angular/router";
import { CategoryService } from "../../services/category";
import * as $ from "jquery";

@Component({
    templateUrl: './index.html'
})

export class CategoryComponent implements OnInit, OnDestroy {
    errorMsg: string;
    CategoryList: any;

    callTable: boolean;
    
    private subscription: Subscription = new Subscription();

    constructor(private service: CategoryService, private router: Router) {
    }

    ngOnInit() {
        this.callTable = true;
        this.FillData();
    }

    ... (truncated for brevity)

Answer №1

Avoid mixing Angular and jQuery as a general rule. The specific issue you're facing is likely due to calling this.FillData() in ngOnInit, which runs every time you navigate to the page. This results in attaching event handlers in jQuery (such as for datatable and onclicks) repeatedly, without detaching them when navigating away. Consequently, the same events get attached multiple times, especially since they're at the Document level using event bubbling.

To address this problem, consider transitioning all your handlers to the proper Angular approach instead of relying on jQuery. If you must use jQuery, refactor your code to remove existing event handlers when routing to or from the component by adding .off('click') within the code. Alternatively, ensure that you attach the event handlers only once in the parent component, given that the events are being bubbled down anyway.

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

A comprehensive guide on displaying data in Angular using an API

I have encountered an issue while trying to display data from an API in the 'home.component.html'. Although my 'home.component.ts' successfully fetches the data from the service, I'm facing difficulty rendering it in 'home.com ...

Discover the method to determine the total count of days in a given week number

I am developing a gantt chart feature that allows users to select a start date and an end date. The gantt chart should display the week numbers in accordance with the ISO standard. However, I have encountered two situations where either the start week numb ...

Upgrade your development stack from angular 2 with webpack 1 to angular 6 with webpack 4

Recently, I have made the transition from Angular 2 and Webpack 1 to Angular 6 and Webpack 4. However, I am facing challenges finding the best dependencies for this new setup. Does anyone have any suggestions for the best dependencies to use with Angular ...

Troubleshooting: The issue of ngModel being undefined in Angular2 with the <input> element

I am currently working with Angular2 and a modified version of Semantic-UI that includes a calendar module. I am utilizing the `calendar` and `dropdown` functionalities: constructor() { setTimeout(() => { jQuery('.ui.dropdown').dr ...

Make sure to verify the existence of a value before attempting to render it in Angular 4

I am currently working on a project that involves Angular 4. Here is an example of the code I am using : <div *ngFor="let item of results"> <p> {{item.location.city}} </p> <p> {{item.location.country}} </p> </div> T ...

Adding the project license to the build in an Angular CLI project for xRay license scanning: A step-by-step guide

Our project has a unique licensing agreement specified in the license attribute within package.json. Upon running ng build, we notice that a 3rdpartylicenses.txt file is created in the dist folder containing licenses for all dependencies except our custom ...

The Angular2 application was constructed using angular-cli, incorporating a directive, and optimized with the ng build

I am working on an angular-cli app and my environment details are: npm -v 3.10.8 node -v v6.9.1 angular2 ^2.4.0 angular/cli 1.0.0-beta.32.3 Recently, I added the following line to my package.json: "angular2-auto-scroll": "1.0.12" You can find more info ...

Is there a way to modify the default lite-server port in the Angular quickstart setup?

I recently obtained the Angular 4 quickstart app and decided to modify the default lite-server port by including "port": 8000 in bs-config.json like this: { "server": { "port": 8000, "baseDir": "src", "routes": { "/node_modules": "node ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

Error encountered while transitioning to Angular 6: "Declining to remove"..."lies beyond"..."and lacks a hyperlink"

As a newbie developer, I am currently working on my first app. Initially, I used Angular 5.2 to build it and now I'm attempting to upgrade to Angular 6. Following the guidelines provided at https://update.angular.io/, I executed the following command ...

What is the best way to transfer data from .ts and .html files to css/scss in an Angular

I'm currently working on a MEAN stack application and I would like to allow users to customize the theme color. The selected color should be saved in MongoDB so that every time the user opens the application, it remains consistent. I would appreciate ...

Angular - optional parameter in route using ngRouter

I have a question regarding using Angular (4) with the @angular/router. I want to be able to include optional parameters in a path style, but am facing some challenges. Currently, my code looks like this: { path: 'cars', component: CarComponent ...

What is the most effective method for structuring JSON data that is utilized by a single-page application (SPA)?

A colleague and I are collaborating on a single page application (built in React, but the framework used isn't crucial; the same query applies to Angular as well). We have a database with 2 interconnected tables: Feature Car Both tables are linked ...

Showing a notification in Angular 4 following a background request

In my page, I have a list of posts that display comments when clicked. Everything is working well, but now I want to show a message if there are no comments for the selected post. Here's how I tried setting up the template: <li *ngFor="let post of ...

The function of TypeScript map is not working properly

Encountering the error message "data.map is not a function" while trying to map data from a REST API request returning JSON data. It appears that the issue may stem from the data structure, as it seems like the returned data should be accessed with data.da ...

Is it possible for dynamically created components to trigger output events?

My objective: Dynamically create components (completed) Enable dynamically created components to utilize "outputs" so that parent Components can listen for changes from the children. Here is a Plnkr showcasing what I am trying to achieve: Plnker -> htt ...

Issues with Angular 5 and Firebase integration

After updating my computer to High Sierra with a clean install, reinstalling the angular-cli, and cloning one of my previous projects that uses Firebase and angularfirebase2, I encountered an issue where any operation to get data from Firebase is not worki ...

Compelling users to provide feedback on an App with the Ionic Framework

As a novice developer, I could use some assistance with implementing ratings in my app. My goal is to show menu items based on whether a user has given my app a 5-star rating. For instance, if a user gives a 5-star rating, I would assign the class "review ...

Troubleshooting: Why is the Array in Object not populated with values when passed during Angular App instantiation?

While working on my Angular application, I encountered an issue with deserializing data from an Observable into a custom object array. Despite successfully mapping most fields, one particular field named "listOffices" always appears as an empty array ([]). ...

Challenge Encountered while Generating Angular Docker Image using VSTS Pipeline

I'm currently in the process of setting up a VSTS pipeline to create a Docker Image for an Angular Application. I've chosen the "Hosted Windows Container" as the Agent pool, but I'm encountering the following error: Step 1/5: FROM nginx:alp ...