What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario:

export class Component {
    condition1: boolean;

    constructor(private confirmationService: ConfirmationService) {}

    submit() {
        this.condition1 = false;
        
        if (somecondition) {
            if (this.condition1 == false) {
                this.confirmationService.confirm({
                    message: "Do you want to proceed?",
                    accept() {
                        // Redirect to another page
                    },
                    reject() {
                        this.condition1 = true;
                    }
                });
            }

            if (this.condition1 == true) {
                this.confirmationService.confirm({
                    message: "Do you want to quit?",
                    accept() {
                        // Perform certain action
                    },
                    reject() {
                        // Perform certain action
                    }
                });
            }
        }
    }
}

Upon clicking the SUBMIT button, a confirm dialog box is displayed. The message in the box depends on the condition set. If the condition one is false, the first message is shown. Upon clicking YES or NO in the dialog box, either the accept() or reject() function is called respectively. In the reject() function, condition1 is set to true. Once condition1 is true, the current dialog should close and immediately open again with a different message based on the outcome of the second if block. How can I achieve this?

Answer №1

Since the specific details of this.service were not provided, I can only assume it acts as a wrapper for window.confirm.

With each invocation of the submit function, condition1 = false; is set, rendering the initial check if (condition1 == false) redundant.

Considering that confirm always results in either true or false, the approach could be revised as follows:

function submit() {
  const redirect = confirm('Do you want to proceed?');
  if (redirect) {
    self.location.href = 'bla/bla/bla';
  } else {
    const quit = confirm('Do you want to quit?');
    if (quit) {
      console.log('I want to quit');
    } else {
      console.log('I do not want to quit');
    }
  }
}

submit();

This implementation should align with your requirements, although detailed information on all code components would have been beneficial.

UPDATE:

Your post modifications have offered more clarity. While my knowledge of Angular is limited, the same logic should apply:

const redirect = this.confirmationService.confirm({
    message: 'Do you want to proceed?',
    accept: () => true, 
    reject: () => false
});

if (redirect) {
    self.location.href = 'bla/bla/bla';
  } else {
    const quit = this.confirmationService.confirm({
        message: 'Do you want to quit?',
        accept: () => true, 
        reject: () => false
    });
    if (quit) {
      console.log('I want to quit');
    } else {
      console.log('I do not want to quit');
    } 
}

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

Styling with CSS: The Art of Showcasing Initials or Images of Individuals

By following this elegant HTML and CSS example, I am able to showcase my initials over my photo. While this is wonderful, I would like the initials to be displayed only if the image does not exist; if the image is present, the person's initials shoul ...

Retrieve Header information when making a cross-domain AJAX request

I've been working on a way to validate image URLs by using an AJAX call to check if the image is still available. The challenge I'm facing is that the image server is on a different domain, so I included the crossDomain: true attribute in my AJAX ...

Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file [ [ { "category": "Bags", "productData": [ { "id": 1000, "name": "Tro ...

Angular: Turn off animations during the first view rendering / page loading

My Angular 4 component features a list of items. I've implemented the Enter and Leave animations following the guidelines in the Angular documentation (https://angular.io/api/animations/animation), but I'm facing an issue where the animation is t ...

Encountering an issue with resolving the module - Material-UI

I am encountering an issue when trying to import a component from 'Material-Ui'. I am currently working with React and Webpack. My goal is to utilize the "Card" component (http://www.material-ui.com/#/components/card). The import statement for C ...

Show the loading icon once to indicate that the page is waiting for an AJAX call

I am currently setting up a table that is refreshed with new data every 4 seconds using AJAX. During the initial page load, I would like to show a loading message while waiting for the AJAX to complete. Currently, I have successfully displayed the loading ...

Encountered an issue with the ProgressPlugin: TypeError - Unable to access property 'tap' of an undefined element

Encountering a Problem with npm run build Here's the issue at hand Compiling client E:\ui\sheraspace_ui\node_modules\webpack\lib\ProgressPlugin.js:223 compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd ...

Exploring the characteristics of $scope elements generated by the $resource factory service within AngularJS

I need to access attributes of an object that originates from a $resource factory service (REST API). services.js: myApp.factory('userService', ['$resource', 'backendUrl', function($resource, backendUrl) { return $resource ...

The Iframe on the webpage is automatically refreshing once a submission is made, which is not a feature present in the original version of

Within my newsletter.html file, I have set up a newsletter where users can submit their email addresses, which are then stored in my JSON file. In homepage.html, I embedded an iframe from the newsletter.html file. Everything seems to be working fine, exce ...

Adjusting canvas dimensions for angular chart.js: A quick guide

I am currently creating my first sample code using angular chart.js, but I am facing an issue with changing the custom height and width of my canvas. How can I adjust the height and width accordingly? CODE: CSS #myChart{ width:500px; he ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

"NodeJS Express: The intricacies of managing overlapping routers

While constructing a NodeJS express API, I have encountered a peculiar bug. It seems that some of the endpoints are overlapping, causing them to become unreachable as the request never completes and ends up timing out. For example: const load_dirs = (dirs ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

Generating JSON on-the-fly with fluctuating keys and values in conjunction with Express JS

When I fetch an API into my Express server, the data comes in the form of JSON key-value pairs within an array. [{ "quality": "best", "url": "https://someurlhere.example/?someparameters" }, { "quality": ...

Requesting data through AngularJS2 HTTP call results in the return of complete PHP code

I am currently facing an issue where my http AJAX call to a local PHP file is echoing the complete PHP code. Since I am new to AngularJS2, I would appreciate some help. Here is the snippet of my AngularJS2 code: makeHttpCall():Promise<any>{ ret ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

What causes CSS to fail to load in React but work normally in Next.js?

We are currently experiencing an issue with a component located in a Git Submodule that is being used by both Next.js and React. While everything is functioning correctly in Next.js, React is unable to accept the way the CSS is being loaded: import styles ...

Deploying Initial Node+Express+Angular Application in Production

Embarking on my first endeavor to develop a Node.js Express app with Angular 7 for deployment in production has me pondering the following: What is the recommended folder structure for this project? Should I maintain separate projects for Node and An ...