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

Restrict access to PHP scripts to only be allowed through AJAX requests

Within my content management system (CMS), I have a specific page that fetches various mini-interfaces from PHP files located in an /ajax directory using AJAX. I am wondering if there is a way to restrict access to these files solely through AJAX requests ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Struggling with getting my Vue-CLI app deployed on Heroku

After diligently following all the steps outlined in this tutorial: https://codeburst.io/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 I encountered an error message when checking my app at: The error indicated: Method Not Allowed ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extend ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

What is the process of converting PUG to JSX?

I am currently attempting to integrate Pug code within a JS react application. While researching, I came across this plugin here, which can assist in converting the code. However, it seems to have an issue with handling the "." statements present in the c ...

What is the best way to add a button click event listener that persists through DOM changes, such as in a single-page application?

I have developed a ViolentMonkey userscript that adds an event listener to a button with the ID #mark-watched. When this button is clicked, it automatically triggers a click on the button with the ID #next-video. This functionality is necessary because the ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...

Is there a way to instruct Babel to generate polyfills such as `__createClass` only once for multiple files?

In my project, I have multiple ES6 files, each containing at least one class. For every file, the __createClass, __interopRequireDefault, and __classCallback polyfilling functions are generated. I plan to concatenate them using browserify, but it seems re ...

The differential treatment of arrays' values in comparison to manually inputted values

Here is a function that I have: public function getReward($formattedArray, $key){ $id = $formattedArray[$key][0]; //dd($id); //Returns 1 $reward = Item::find($id); return $reward; } The problem arises when executing this part of the code ...

What methods can be used to send JSON data in the body of an express router.get request?

I am currently working on setting up an express endpoint to fetch data from an API and return the JSON response in the body. We are receiving JSON data from a rest API as an array and my goal is to utilize express router.get to present this formatted JSON ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

Using a PHP variable within an AJAX modal window: A step-by-step guide

The main page (main.php) is currently holding a variable called $var = "hello". A modal window (modal.php) is being loaded through AJAX utilizing the following script: var modal_xhr = $.ajax({ 'type' : 'GET', ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...

Is there a way to change the URL in the address bar without refreshing the page?

Is it possible to update the URL in the address bar without reloading the page? I came across 2 potential solutions: Option 1: Check out this link It involves using window.history.replaceState. But when I tried implementing it in my angularjs projec ...

What is the best way to achieve complete code coverage for ajax requests, including success and failure callbacks, using Jasmine and Blanket.js?

Here is a sample code snippet for adding a row: var Utils = {}; Utils.genericAddRowPost = function(url) { return $.post(url); }; Utils.genericAddRow = function(dataSource, url) { genericAddRowPost(url).done(function(data, textStatus, jqXHR) { ...

Steps to retrieve specific text or table cell data upon button click

Greetings, I am a beginner in the world of html and javascript, so please bear with me :) My challenge involves working with a table in html. Each row contains a dropdown menu (with identical options) and a button. When the button is clicked, I aim to sen ...

What is the best way to adjust the size of an image as I navigate down a webpage?

I've been working on designing a navigation bar for a website, but I'm running into some issues. My goal is to have the logo shrink as the user scrolls down the site. I've experimented with webkit animations and various javascript/jQuery fun ...

Tips on applying a class to a host element using @hostbinding in Angular 2

I've been wanting to assign a class to the host element of my component, and initially I used the host property in this manner: @Component({ selector: 'left-bar', host: { 'class': 'left-bar' }, templateUrl: 'a ...

Improving the utilization of services in Angular

I have a DatesService that handles date manipulation. Additionally, I have two services that require date manipulation - EventsService and CalendarService. The CalendarService utilizes the EventsService. My query is: what would be more efficient (in terms ...