Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() function, allowing me to either cancel or revert the dragged item before the move is completed.

Incorporating my modal into this process looks something like this:

let subscription = this.modalService.onSubmit.subscribe((val) => {

This modal subscription essentially waits for the user to click on either OK or CANCEL in the modal window that asks, "Are you sure you want to move this item?"

The issue arises when the other event subscription (dragula) does not wait for the modal event subscription to conclude; dragula completes before the modal confirmation takes place, causing problems for me as calling drake.cancel results in an error due to the absence of the necessary elements.

CODE :

this.dragulaService.drop.subscribe(
    value => {
        let modal: ModalComponent = this.modalService.GetModal();
        let subscription = this.modalService.onSubmit.subscribe((val) => {
            // If the user clicks OK, no action is taken and the drag-drop operation concludes successfully
            // If the user clicks Cancel, we call this.dragulaService.find('bag-deals').drake.cancel(true);

Answer №1

To enhance your code, consider incorporating a concatMap into your pipe. Check out this informative article on Higher-Order RxJS Mapping Operators for more details.

In your specific scenario, I implemented it in the following manner:

    let dropValue;
    this.dragulaService.drop
      .pipe(concatMap(value => {
        dropValue = value;
        const modal: ModalComponent = this.modalService.GetModal();
        return this.modalService.onSubmit;
      })).subscribe(value => {
         //If the user clicks OK, we proceed with the drag and drop operation as usual.
         //If they click Cancel, we call this.dragulaService.find('bag-deals').drake.cancel(true);
    });

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

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

Ways to enhance the functionality of an input component

Within my React app, I have an input component that triggers an onChange event when connected to another component: <input type="text" onChange={onChange} /> Now, I am looking to enhance this input component by incorporating a prop from another com ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...

The Chip Component in MUI dynamically alters its background color when it is selected

Currently, I am working on a project in React where I am utilizing the MUI's Chip component. My goal is to customize this component so that it changes its background color when selected, instead of sticking to the default generic color. https://i.sta ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

Avoid re-rendering the page in Nuxt when adjusting dynamic parameters

My page has two dynamic parameters that trigger the fetch method to run again when the URL params are changed. I want to avoid this behavior. Fetch Method: async fetch() { await this.getFlightResult(); } Get Result Method: async getResult() { th ...

Error occurred due to a reference to a function being called before it was

Occasionally, I encounter a "Reference Error" (approximately once in every 200 attempts) with the code snippet below. var securityPrototype = { init: function(){ /* ... */ }, encryptionKey: function x() { var i = x.identifier; ...

Tips for showcasing the popover content on a separate page?

Whenever I click on "Choose City," a popover will appear containing two cities: 'Bengaluru' and 'Hyderabad.' If I select Bengaluru, the city name should be displayed instead of "Choose City." home.html: <ion-header> <button ...

Generate a new Angular2 component on the fly based on information retrieved from an API request

Within my application, I have implemented a dropdown menu featuring 'Statements' that users can select. Upon the selection of a specific statement, an API call is triggered to fetch data on how this information should be displayed, referred to as ...

I require the variable to be accessible from all corners

Is there a way to access the variable "finalPrice" in a different function? I'm trying to achieve this and could use some guidance. function available(id){ $.ajax({ method:"GET", }).done(function(data){ for( ...

JavaScript - Attempting to Add Objects to Array Unsuccessful

After seeing this question raised multiple times, I am determined to find a solution. In my current project, I am tasked with displaying a list of orders and implementing a filter by date functionality. However, I keep encountering an error when trying to ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

Merging double borders in a div using CSS is essential for creating

Upon examining this sample, it's evident that the borders do not blend together. css: div{ float:left; background-color:moccasin; width:100px; height:100px; border:1px solid tomato; } The number of divs is arbitrary, and only on ...

Using custom types for prop passing in Next.js with TypeScript

After making a http call, I obtain an array containing JSON data. This data is then assigned to a type called Service. type Service = { id?: string; name?: string; description?: string; }; The api call is made in getServerSideProps and the Service type is ...

Arrange items in a particular order

I need help sorting the object below by name. The desired order is 1)balloon 2)term 3)instalment. loanAdjustmentList = [ { "description": "Restructure Option", "name": "instalment", " ...

JavaScript: Converting an array of strings into an array of objects with proper formatting

After scanning barcodes, I have an array of strings that currently contains the following data: var array = ['NEW', '1111', 'serial1', 'serial2, 'NEW', '2222', 'serial3', 'serial4'] ...