Exploring the behavior of control flow in Typescript

I am a beginner when it comes to JS, TS, and Angular, and I have encountered an issue with an Angular component that I am working on:

export class AdminProductsMenuComponent implements OnInit{
    constructor(private productService: ProductService,
                private alertService: AlertService,
                private router: Router) {
                    this.subscribeToDeleteProductEvents();
    }

    productsAdminModel: IGetProductAdminModel[] = [];
    private productId: string;

    ngOnInit(): void {
        this.executeGetAllProductsAsAdmin();
    }

    executeGetAllProductsAsAdmin() {
        this.productService.getAllProductsAsAdmin().subscribe({
            next: (productData) => this.productsAdminModel = productData
        })
    }

    private subscribeToDeleteProductEvents() {
        this.alertService.getSubjectAlertEvent().subscribe({
            next: (isConfirmed) => {

                if (isConfirmed) {
                    this.productService.deleteProduct(this.productId).subscribe({
                        next: () => {
                            this.reloadCurrentResources();
                        }
                    });
                }
            }
        });
    }

    private reloadCurrentResources(): void {
        // save current route first
        this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
            this.router.navigate(['/AdminProducts']); // navigate to the same route
        }); 
    }

    executeProductDelete(id: string) {
        this.productId = id;
        this.alertService.confirmationAlertProductDelete();
    }
    
}

In summary: The constructor has a subscription in place to listen for events throughout the component's lifecycle.

An event is triggered by the last method called (via the template), which displays a SweetAlert confirmation dialog. Depending on the selection made, the event can be either true or false.

However, there seems to be an issue - if I move the executeProductDelete() method above reloadCurrentResources() and subscribeToDeleteProductEvents() and invoke it (executeProductDelete), an error occurs. https://i.sstatic.net/VXX7n.png

I suspect that it triggers once again the subscribeToDeleteProductEvents() and reloadCurrentResources().

If I keep executeDeleteProduct() as the final method, no error arises. Why is this happening? I think they are running synchronously and are not being called anywhere else.

Answer №1

It appears that there are two primary issues to address:

  1. Do your best to avoid constantly "reloading" the same component, instead, abstract the reload logic into separate methods. This practice can lead to strange issues and unnecessary data loads, as single page applications (SPAs) are meant to function seamlessly without constant reloading.

  2. If you find yourself repeatedly reinstalling the component through your reloadResources function, the alert service's behavior subjects may be creating new subscriptions each time. If these subscriptions are not properly unsubscribed from, they will continue to listen indefinitely.

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

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

Can you explain the meaning of the symbol '&$checked'?

import React from 'react'; import Checkbox from '@material-ui/core/Checkbox'; import { createMuiTheme, makeStyles, ThemeProvider } from '@material-ui/core/styles'; import { orange } from '@material-ui/core/colors'; ...

Eliminating memory leaks in a React web application

I'm facing an issue in my ReactJS web application with the following code: useEffect(() => { const fetchInfo = async () => { const res = await fetch(`${api}&page=${page}`); setLoading(true); try { const x = awa ...

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

The handler for errors in DRW consistently generates the message "Error" instead of providing specific information about the issue at hand

FiltersManager.getAllServices({ callback : updateServiceFilter, errorHandler : function(message) { alert(message); } }); Although I throw an exception when an error occurs in th ...

Adjust the Material UI card to fill the maximum available height

I'm currently working with Material UI Card components. You can find more information here. My goal is to set a maximum height for these cards, ensuring that the text and images are displayed nicely. How should I approach this? Below is a snippet of ...

Steps to display a text box once the dropdown list is updated

I have a dropdown menu with two options <div class="form-group"> <span class="col-sm-4 control-span">Member Type</span> <div class="col-sm-8"> <select class="form-control" id="membertype" name="me ...

Using NextJS's API routes to implement Spotify's authorization flow results in a CORS error

I am currently in the process of setting up the login flow within NextJS by referring to the guidelines provided in the Spotify SDK API Tutorial. This involves utilizing NextJS's api routes. To handle this, I've created two handlers: api/login.t ...

Issue with ion-select default value not being applied

In my ion-select element, I have multiple options and I want to set a default value based on the CurrentNumber when the view is loaded. Here's the code snippet: <ion-select formControlName="Level"> <ion-option [value]="level.id" *n ...

The function tokenNotExpired encounters an error when attempting to access the localStorage, as it

I am looking to incorporate the angular2-jwt library into my project: https://github.com/auth0/angular2-jwt However, I encountered an exception when attempting to call the tokenNotExpired function: Exception: Call to Node module failed with error: Refe ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

What is the best way to insert images into a div in Ionic framework?

I am facing an issue with fitting an image inside a div container. Here is my code structure: <div style="background-color: red; height: 200px; width: 200px;"> <ion-img src="{{kategori[i].img}}"></ion-img> & ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Design interactive Vue form with customized questions based on user response

I am looking to dynamically create a form with conditional fields. The structure of the form is stored in an object called Q. Below is an example of a Vue component that utilizes bootstrap-vue. <template> <div> <div v-for="q of ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Three divs are set in place, with two of them of fixed width while the third div is

Looking for a layout with specific positioning and fixed widths: One box on the left, one box on the right, each with a width of 200px. The middle div should adjust to take up the remaining space. Any suggestions are appreciated. Thank you! ...