Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example:

["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"]

I iterate through this array and based on the index, I execute different .subscribe functions and add data to a new array.

for (var i = 0; i < arrayOfItems.length; i++) {  
    switch (arrayOfItems[i]) {
        case 'spells':
            this.spellsSubscribeSet = true;
            this.spellsSubscribe = this.spells.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        case 'characters':
            this.charactersSubscribeSet = true;
            this.charactersSubscribe = this.characters.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        case 'consumables':
            this.consumablesSubscribeSet = true;
            this.consumablesSubscribe = this.consumables.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        default:
            return null;
    }
}

The function .getRandom is just a simple method that generates a random number.

getRandom(x) {
    return Math.floor(Math.random() * x);
}

An interesting thing is that only 'spells' are executed multiple times.

I've heard about .flatMap but I don't think it will help me in this scenario since I'm working with a regular array.

This code snippet works with a Firestore database.

Answer №1

During the initialization of the constructor, I stored all the necessary information and retrieved it at a later point in the code when required.

Answer №2

Your loop may be encountering the 'spells' case multiple times, causing it to subscribe multiple times to the spells events and resulting in the code within the subscription being executed multiple times.

In order to avoid this issue, you should consider checking if you have already subscribed to that event. You can implement a check like the following:

if (!this.spellsSubscribeSet) {
    this.spellsSubscribeSet = true;
    this.spellsSubscribe = this.spells.subscribe(data => {
        const spellId = this.getRandom(data.length - 1);
        this.activeSpells.push(data[spellId]);
    });
}
break;

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

Looking for a particular value within a multidimensional $_SESSION array - here's how!

In my coding project, I am utilizing a $_SESSION array to keep track of item details such as description, quantity, and price for items added to a shopping cart. The initial part of the code functions smoothly, as shown below: $quantity = 1; // add first ...

Access and retrieve real-time JavaScript variables directly from a website

Question: I am curious about the possibility of accessing JavaScript variables on a website from C#. Since the scripts are on the client side, is it possible to read their values live through C#? Any assistance or guidance on this matter would be greatly ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

I am having trouble getting my angular image to switch using angular animations

I am attempting to implement image swapping using Angular animations based on a 10-second timer. However, the swap is not occurring and I have been troubleshooting without success. The goal is for the images to change when the timer reaches 5 seconds, but ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

Accessing and parsing JSON data from directories within directories

My file directory structure is dynamic, with only the name of $(Root Directory) known at runtime. All folders and files are generated dynamically, with all files being in .json format. I am looking to count the number of files and read the content of eac ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

Navigate to the top of the page using jQuery

Attempting to implement a simple "scroll jump to target" functionality. I've managed to set it up for all parts except the "scroll to top". The jumping works based on the tag's id, so it navigates well everywhere else, but not to the very top. He ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

Determine the total cost based on the quantity purchased

I created a webpage for employees to select an item from a dropdown menu, and it will automatically display the price of that item. Check out my code below: <script> $(document).ready(function() { $('#price_input').on('change' ...

Enhancing a Given Interface with TypeScript Generics

I am looking to implement generics in an Angular service so that users can input an array of any interface/class/type they desire, with the stipulation that the type must extend an interface provided by the service. It may sound complex, but here's a ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": This is how my media.component.ts file is structured: import { Component, Input } from &apo ...

What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation. Check out this code snippet on jsFi ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Tips for avoiding the display of concealed forms on a webpage

Hey there, I'm just starting out with html forms and currently experimenting with Jquery to hide forms upon loading the page. However, I've encountered an issue where some forms briefly appear before hiding after the page finishes loading. Here& ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Why won't the function activate on the initial click within the jQuery tabs?

When creating a UI with tabs, each tab contains a separate form. I have noticed that when I click on the tabs, all form save functions are called. However, if I fill out the first tab form and then click on the second tab, refresh the page, and go back t ...

Exploring the world of dynamic locale with Angular 5 Pipes

My current situation involves having apps created in angular 4 and I am contemplating upgrading to angular 5. After researching how locale is managed in the pipes, it appears that upgrading may not be feasible. It seems that there are two options provided: ...